I am not sure if I am doing it wrong or there is some issue when handling unique constraint when working with GenericForeign Relations in Django.
When I try to save an object (in Admin for example) I get unique constraint error (raises 500) form database but not ValidationError on Admin (UI).
Below is my code snippet,
I have one generic relation model as below,
class Targeting(models.Model):
TARGETING_CHOICES = (
('geo', "Geo targeting"),
('other', "Other targeting"),
)
targeting_type = models.CharField(max_length=64, choices=TARGETING_CHOICES, null=False)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Meta:
unique_together = ('content_type', 'object_id', 'targeting_type')
And my other model using it is,
class MyModel(models.Model):
name = models.CharField(max_length=60, db_index=True)
targeting = GenericRelation('Targeting')
Exception Raised:
duplicate key value violates unique constraint "mymodel_targeting_targeting_type_0dff10ee_uniq"
DETAIL: Key (targeting_type, content_type_id, object_id)=(geo, 18, 188) already exists.
Is there something wrong with way I implemented it ? or something is not meant to used like this ?
Any sort of help is really appreciated. Thanks