Unique together constraint including specific field value

后端 未结 3 1746
面向向阳花
面向向阳花 2021-02-15 10:25

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\'

3条回答
  •  醉话见心
    2021-02-15 10:47

    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

提交回复
热议问题