Ale*_*x T 4 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')
Run Code Online (Sandbox Code Playgroud)
然后我继承它:
class Question(GFKModel):
author = models.ForeignKey(User)
text = models.TextField()
class Meta:
unique_together = ('author', 'target_content_type', 'target_id')
Run Code Online (Sandbox Code Playgroud)
我需要在 '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.
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
我错过了 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
Run Code Online (Sandbox Code Playgroud)
现在它按预期工作。
| 归档时间: |
|
| 查看次数: |
2615 次 |
| 最近记录: |