Django unique_together模型父类字段



我想用呈现 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')

我需要在"作者"、"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.

我该怎么做?

我错过了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

现在它按预期工作。

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

但是,如果您使用混凝土基础模型,则不能使用unique_together

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

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

最新更新