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

查看:33
本文介绍了如何删除 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)

如果我直接使用Bussinesses,Django会访问数据库中的bussiness_bussiness"表,这个表显然不存在.

If I use Bussinesses directly, the Django will access the "bussinesses_bussinesses" table in the database, which obviously does not exist.

因为表businesses"也被其他APP使用,所以不能重命名.我想知道如何在不使用表前缀的情况下使用Django模型,也不想直接使用原始数据库API.

Because the table "bussinesses" is also used by another APP, So can't rename it. I want to know how to use the Django 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"

顺便说一句,businesss 拼写错误.由于您正在指定表的名称,因此您不必为模型提供与表相同的名称,因此如果表名称拼写错误并且您无法轻松修复它,您至少可以更改名称businesss 的正确拼写.我也会去掉复数,并使其成为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天全站免登陆