I want to generalize my workflow with models where presented GenericForeignKey fields.
So I create parent class 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')
Then I inherit it:
class Question(GFKModel):
author = models.ForeignKey(User)
text = models.TextField()
class Meta:
unique_together = ('author', 'target_content_type', 'target_id')
I need to add unique_together constraint on both 'author', 'target_content_type' and 'target_id', but I can't do that due to migration error:
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.
How can I do that?
I've missed declaration of GFKModel as 'abstract' class:
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
Now it works as expected.