Unique together constraint including specific field value

后端 未结 3 1765
面向向阳花
面向向阳花 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条回答
  •  Happy的楠姐
    2021-02-15 11:07

    In addition to the previous answer you can overwrite the save() method. It would be something like this:

    def save(self, **kwargs):
        try:
            self.objects.get(field_a=self.field_a, field_b=self.field_b, validated=True)
    
            # The object already exist therefore throw an exception
            raise ValidationError(
                "field_a and field_b must be unique if validated=True"
            ) 
    
        except self.__class__.DoesNotExist:  # Save the model
            super(MyModel, self).save(**kwargs)  # inherit and call the save method
    

    Now you don't need to call the clean() method.

提交回复
热议问题