在Django中更改表名 [英] Change table name in Django

查看:269
本文介绍了在Django中更改表名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读到可以使用元选项自定义Django中的表名。我想知道如何使用db_table选项来继续使用应用程序名称,而无需对应用程序名称进行硬编码就可以稍微修改模型名称。

I have read that the table name in Django can be customized using Meta Options. I'm wondering how the db_table option could be used to keep using the app name but modify the model name slightly without hardcoding the app name.

例如,来自Django教程中,应用程序名称为民意调查,模型名称为民意调查。可以说我希望将该表称为 polls_mypoll,而不是 polls_poll。这是我尝试过的方法,但是无法访问外部类(未定义轮询)

For example, from the Django tutorial, the app name is "polls" and the model name is "poll". Lets say I want the table to be called "polls_mypoll" instead of "polls_poll". Here is what I tried, but the outer class cannot be accessed (Poll is not defined)

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    class Meta:
        db_table = "%s_%s" % (Poll._meta.app_label, "mypoll")

类似地,如果我想要明确定义db_table只是默认的polls_poll?我知道我可以完全不使用Meta类,而将使用默认名称,但是如果我想明确一点怎么办?

Similarly, what if I wanted to define db_table explicitly to just be the default polls_poll? I know I could just leave off the class Meta entirely and that default name would be used, but what if I wanted to be explicit about it?

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    class Meta:
        db_table = "%s_%s" % (Poll._meta.app_label, Poll._meta.model_name)

这是行不通的,再次是因为未在Meta中定义投票。

This doesn't work, again because Poll is not defined inside Meta.

推荐答案

未定义轮询,是您的异常,由您的 db_table =%s_%s%(Poll._meta.app_label,Poll._meta.model_name)语句引用 Poll 类,仍在构建中(尚未插入到全局范围中)。如果要在 db_table 中使用对 Poll 的引用,请考虑编写自己的从 ModelBase ,并设置 _meta.db_table 值正确。届时,投票名称将不可用,但实际对象将被构造并由您操作。

The exception you are getting, Poll is not defined, is caused by your db_table = "%s_%s" % (Poll._meta.app_label, Poll._meta.model_name) statement referencing the Poll class while it is still being constructed (not yet inserted into the global scope). If you want to use references to Poll in the db_table, consider writing your own metaclass that inherits from ModelBase, and sets the _meta.db_table value properly. At that point, the Poll name won't be available, but the actual object will be constructed and at your hand to manipulate.

这篇关于在Django中更改表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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