2016-04-24 88 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 

現在按預期工作。