【问题标题】:Django unique_together on model parent class fields模型父类字段上的 Django unique_together
【发布时间】:2016-08-17 20:52:35
【问题描述】:

我想用呈现 GenericForeignKey 字段的模型来概括我的工作流程。

所以我创建了父类GFKModel:

class GFKModel(models.Model):
    target_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    target_id = models.PositiveIntegerField()
    target = GenericForeignKey('target_content_type', 'target_id')

那我继承它:

class Question(GFKModel):
    author = models.ForeignKey(User)
    text = models.TextField()

    class Meta:
        unique_together = ('author', 'target_content_type', 'target_id')

我需要在“author”、“target_content_type”和“target_id”上添加 unique_together 约束,但由于迁移错误,我不能这样做:

qna.Question: (models.E016) 'unique_together' refers to field 'target_content_type' which is not local to model 'Question'.
HINT: This issue may be caused by multi-table inheritance.

我该怎么做?

【问题讨论】:

    标签: django inheritance django-models


    【解决方案1】:

    我错过了将 GFKModel 声明为“抽象”类:

    class GFKModel(models.Model):
        target_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
        target_id = models.PositiveIntegerField()
        target = GenericForeignKey('target_content_type', 'target_id')
    
        class Meta:
            abstract = True
    

    现在它可以按预期工作了。

    【讨论】:

      【解决方案2】:

      Alex T 的解决方案适用于抽象基础模型

      但是,如果您使用混凝土基础模型,您 cannot use unique_together

      更多关于 Django 中不同的多态类型:

      https://realpython.com/modeling-polymorphism-django-python/#concrete-base-model

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-12
        • 1970-01-01
        • 1970-01-01
        • 2013-05-06
        • 1970-01-01
        • 1970-01-01
        • 2010-12-27
        • 2012-01-05
        相关资源
        最近更新 更多