Unique together constraint including specific field value
django, python
Solution
You can use UniqueConstraint in case you're using Django 2.2+ Here is an example
class MyModel(models.Model):
field_a = models.CharField()
field_b = models.CharField()
validated = models.BooleanField(default=False)
class Meta:
constraints = [
UniqueConstraint(fields=['field_a', 'field_b'], condition=Q(validated=True), name='unique_field_a_field_b_validated')
]
here is the source
Problem
For one of my models, I need to ensure the unicity of some rows, but only in a certain case. Only the "validated" rows should follow this constraint. Basically, I'm looking forward something like ``` class MyModel(models.Model): field_a = models.CharField() field_b = models.CharField() validated = models.BooleanField(default=False) class Meta: unique_together = (('field_a', 'field_b', 'validated=True'),) ```