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