Hi folks (and in particular Simon Charette),
I had a bit of a gotcha moment when a custom unique constraint validation message disappeared when I added a condition to it. I won't raise a ticket for this because it looks intentional from the constraint validation PR, but I wanted to seek clarification and whether either some adjustment to the behaviour could be made or clarification in the docs.
Here's a boiled down example:
Validating models with UniqueConstraint usually groups errors by field name:
class Test(Model):
test = CharField(max_length=255)
class Meta:
constraints = [
UniqueConstraint(fields=["test"], name="unique"),
]
Test.objects.create(test="abc")
test = Test(test="abc")
test.validate_constraints()
django.core.exceptions.ValidationError: {'test': ['Test with this Test already exists.']}
However if a condition is added to the UniqueConstraint the validation error is categorised as a non-field error:
class Test(Model):
test = CharField(max_length=255)
class Meta:
constraints = [
UniqueConstraint(fields=["test"], name="unique", condition=~Q(test="")),
]
Test.objects.create(test="abc")
test = Test(test="abc")
test.validate_constraints()
django.core.exceptions.ValidationError: {'__all__': ['Constraint “unique” is violated.']}
I was wondering what the rationale for that was? Would it be possible to make the behaviour consistent? And if not - would a PR to clarify how ValidationErrors are raised for constraints in the docs be welcomed?
Cheers,
David