[Django]-Unique_together constraint on multiple columns with NULL values

5👍

There’s no way to tell django to add that index I’m afraid, unique_together only handles simple indexes. However, you can validate at the model layer using the clean method, which you should call before saving your model instance (ModelForm instances call it for you):

from django.core.validators import ValidationError

class Part(models.Model):

    def clean(self):
        duplicates = Part.objects.exclude(pk=self.pk).filter(name=self.name)
        if self.brand:
            duplicates = duplicates.filter(brand=self.brand)
        if duplicates.count():
            raise ValidationError(u'Duplicate part/brand')

Ideally you should manually add the index to your Postgres database, using a RunSQL operation in your migrations.

👤Greg

Leave a comment