django-rest-framework icon indicating copy to clipboard operation
django-rest-framework copied to clipboard

Add support of custom violation_error_code for UniqueTogetherValidator

Open znotdead opened this issue 11 months ago • 0 comments

Will be nice to have an option to pass custom code for ValidationError based on name of UniqueTogether constraint as it's unique or better to use violation_error_code . Line to fix: Link to the line for fix - here is is hard coded to code='unique'

Example:

class Pet(models.Model):
    name = models.CharField(max_length=100)
    animal_type = models.CharField(max_length=100)
    owner_name = models.CharField(max_length=100)

    class Meta:
        constraints = [
            UniqueConstraint(
                fields=["name", "animal_type"],
                name="unique_pet",
                violation_error_code="unique_pet",
            ),
            UniqueConstraint(
                fields=["owner_name", "animal_type"],
                name="unique_pet_type",
                violation_error_code="unique_pet_type",
            ),
        ]

If there are 2 different constraints there is no way to distinguish errors to know which constraint failed as all errors always have code unique and look like: [{'non_field_errors': [ErrorDetail(string='The fields name, animal_type must make a unique set.', code='unique')]}] For code name attr of constraint can be used. And error could looks like: [{'non_field_errors': [ErrorDetail(string='The fields name, animal_type must make a unique set.', code='unique_pet_type')]}]

znotdead avatar Jun 02 '25 22:06 znotdead