Skip to content

Add support of custom violation_error_code for UniqueTogetherValidator #9714

@znotdead

Description

@znotdead

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')]}]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions