【问题标题】:Django: app_label problem when declaring base models outside models.pyDjango:在models.py之外声明基本模型时出现app_label问题
【发布时间】:2011-01-25 09:08:07
【问题描述】:

我有一个抽象的 Container 类,它允许派生模型保存一些内容块,例如图像、文本等,它们也是单独的模型。对于数据库整洁,我希望将这些模型的表标记为 content_block_image、content_block_text 等。

但是当我在 Content 模型的 Meta 类中指定 app_label = 'content_block' 时,我在 syncdb 期间收到错误:

content.event: 'content' 与模型 Content 有 m2m 关系,该模型要么尚未安装,要么是抽象的。

我声明以下基类如下:

# base.py
class Content(models.Model):
    tags = models.TextField(_('tags'), blank=True)
    user = models.ForeignKey(User)
    content_type = models.ForeignKey(ContentType, 
                                     related_name='%(class)s_content_set')

    container_type = models.ForeignKey(ContentType)
    container_id = models.PositiveIntegerField()
    container = generic.GenericForeignKey('container_type', 'container_id')

    class Meta:
        app_label = 'content_block'

class Container(models.Model):
    content_type = models.ForeignKey(ContentType, 
                                     related_name='%(class)s_container_set')
    content = generic.GenericRelation('Content', 
                                      content_type_field='container_type', 
                                      object_id_field='container_id')
    class Meta:
        abstract = True

然后,在我的模型中,我声明了我称之为容器的模型,例如:

# models.py
class Event(Container):
    title = models.CharField(max_length=100)
    start = models.DateTimeField()
    end = models.DateTimeField()

如果我删除app_label,syncdb 运行没有问题。看来 app_label 不仅仅是一个标签。

关于如何使用 Content 基类集的 app_label 进行此操作的任何想法?

【问题讨论】:

    标签: django inheritance django-syncdb


    【解决方案1】:

    来自the doc

    如果模型存在于标准 models.py 之外(例如,如果应用的模型位于 myapp.models 的子模块中),则模型必须定义它属于哪个应用:

    app_label = 'myapp'
    

    content_block 应用程序存在吗?如果没有,我不确定它会起作用。

    看来你想要做的是强制表名。这个属性是可能的

    用于模型的数据库表的名称:

    db_table = '音乐专辑'

    【讨论】:

    • 你是对的,db_table 是参数。但是,由于这是其他人继承的基本模型,我希望所有继承的模型都以该格式命名。因此它应该接受类似于related_name字段属性的类名参数,即db_table = content_block_%(class)s,但它不接受。
    • 如何从 Meta 类中访问继承模型的模型名称? db_table 属性可以通过db_table = content_block_%s % inheriting_model_name 等参数化吗?
    猜你喜欢
    • 2017-03-05
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多