I have a class, which represents photos attached to a person.
JavaScript
x
8
1
class PersonPhoto(models.Model):
2
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
3
photo = models.FileField(upload_to='photos/', blank=True, null=True)
4
person = models.ForeignKey(
5
Person, related_name="photos", on_delete=models.CASCADE
6
)
7
main = models.BooleanField(default=False)
8
I want to make sure that for every person there could be only one main photo. In pure SQL i would use something like
JavaScript
1
3
1
create unique index on photo (person_id, main)
2
where main = true;
3
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
JavaScript
1
13
13
1
class PersonPhoto(models.Model):
2
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
3
photo = models.FileField(upload_to='photos/', blank=True, null=True)
4
person = models.ForeignKey(
5
Person, related_name="photos", on_delete=models.CASCADE
6
)
7
main = models.BooleanField(default=False)
8
9
class Meta:
10
constraints = [
11
models.UniqueConstraint(fields=['person'], condition=models.Q(main=True), name='unique_person_main'),
12
]
13