如何去除Django模型的表格前缀? [英] How to remove the prefix of a table for a Django model?

查看:1064
本文介绍了如何去除Django模型的表格前缀?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个名为Bussinesses的新django应用程序(而不是项目),然后将以下类添加到models.py。

I create a new django app(not project) called Bussinesses, then add following class to the models.py.

class Bussinesses(models.Model):
    business_email = models.EmailField()
    password = models.CharField(max_length=20)
    contact_first_name = models.CharField(max_length=30)
    contact_last_name = models.CharField(max_length=30)

如果我直接使用Bussiness,django将会访问数据库中的bussinesses_bussinesses表,显然不存在。

if i use Bussinesses directly, the django will access the "bussinesses_bussinesses" table in the database, It obviously does not exist.

因为表bussinesses也被另一个APP使用,所以不能重命名它。
我想知道如何使用Djano模型而不使用表前缀,我不想直接使用原始数据库API。

Because the table "bussinesses" is also used by another APP, So can't rename it. I want to know how to use the Djano model without using table prefix, and i don't want to use the raw database API directly.

谢谢

推荐答案

只需使用模型元选项

class Bussinesses(models.Model):
    business_email = models.EmailField()
    password = models.CharField(max_length=20)
    contact_first_name = models.CharField(max_length=30)
    contact_last_name = models.CharField(max_length=30)

    class Meta:
        db_table = "bussinesses"

BTW 企业拼写错误。由于您指定了表的名称,因此无需为模型提供与表相同的名称,因此如果表名拼写错误,并且您无法轻松修复它,您至少可以更改名称您的班级正确拼写企业。我也会摆脱多元化,并使它成为 class Business 。最后,在现有数据库上使用Django或Rails需要为每个表设置自定义表名称并不罕见。

BTW businesses is misspelled. Since you're specifying the name of the table you don't have to give your model the same name as the table, so if the table name is misspelled and you can't easily fix it, you can at least change the name of your class to the proper spelling of businesses. I would also get rid of the pluralization, and make it class Business. Finally it's not uncommon when using Django or Rails on an existing database to need to set a custom table name for every table.

这篇关于如何去除Django模型的表格前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆