3

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

Adeel
  • 761
  • 7
  • 24

1 Answers1

0

You won't receive ValidationError here, because it can't be validated without additional query and django won't create that query by itself. If you need to have that validation, you need to write it by yourself.

GwynBleidD
  • 20,081
  • 5
  • 46
  • 77