模型父类字段上的 Django unique_together

标签 django inheritance django-models

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

我怎样才能做到这一点?

最佳答案

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

现在它按预期工作。

关于模型父类字段上的 Django unique_together,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36824068/

相关文章:

C++ 动态对象。运行时如何确定对象大小?

django - 每个模型多个图像

python - 在运行时向 Django 模型添加属性?

html - 形成具有相同字段的 POST HTML

python - ModelForm 的表单类可以更改属性吗?

django - "Returning to that page might cause any action you took to be repeated"- Django

javascript - 使用 JS 多态性和方法重写

javascript - 原型(prototype)继承应该节省内存吧?

python - 在Django中继承外键->'self'关系中的特定父模型属性

django - 如何为 django model.FileField 生成唯一的文件名