Skip to content
Advertisement

Django index unique on where

I have a class, which represents photos attached to a person.

class PersonPhoto(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    photo = models.FileField(upload_to='photos/', blank=True, null=True)
    person = models.ForeignKey(
        Person, related_name="photos", on_delete=models.CASCADE
    )
    main = models.BooleanField(default=False)

I want to make sure that for every person there could be only one main photo. In pure SQL i would use something like

create unique index on photo (person_id, main) 
where main = true;

You can play with it here http://sqlfiddle.com/#!15/34dfe/4

How to express such constraint in django model? I am using django 4.0.1

Advertisement

Answer

You can add a UniqueConstraint to your model Meta.constraints with a condition to enable this constraint

class PersonPhoto(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    photo = models.FileField(upload_to='photos/', blank=True, null=True)
    person = models.ForeignKey(
        Person, related_name="photos", on_delete=models.CASCADE
    )
    main = models.BooleanField(default=False)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['person'], condition=models.Q(main=True), name='unique_person_main'),
        ]
Advertisement