我想用提供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‘上添加target_content_type约束,但是由于迁移错误,我不能这样做:
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.我怎么能这么做?
发布于 2016-04-24 14:27:33
我错过了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现在,它如预期的那样工作。
发布于 2019-12-06 11:47:37
Alex T的解适用于抽象基模型
但是,如果使用具体的基本模型,则需要together
更多关于Django中不同多态性类型的信息:
https://realpython.com/modeling-polymorphism-django-python/#concrete-base-model
https://stackoverflow.com/questions/36824068
复制相似问题