2016-04-24 70 views
2

我想概括我的工作流与提供GenericForeignKey字段的模型。Django unique_together模型父类字段

所以我创建父类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. 

我该怎么做?

回答

2

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

现在按预期工作。