What I get instead is a database-level integrity error.
If the condition field is editable, I do get a validation error (although
a form level one, not a field level one, which might be another bug).
If there is no condition on the field, I do get the expected field level
validation error.
Example:
{{{
class Thing(models.Model):
name = models.CharField(max_length=10)
status = models.CharField(max_length=10, blank=True, editable=False)
class Meta:
constraints = [
models.UniqueConstraint(
fields=["name"],
name="thing_unique_name",
condition=~Q(status="archived"),
)
]
}}}
Small test case repo:
https://github.com/salomvary/django_partial_constraint_bug
(To reproduce, go to http://127.0.0.1:8000/admin/thing/thing/add/ and try
to add two Things with the same name.)
I've tried the latest dev version of Django, which has same problem.
--
Ticket URL: <https://code.djangoproject.com/ticket/34166>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* Attachment "Screen Shot 2022-11-16 at 16.16.17.png" added.
Expected error
* Attachment "Screen Shot 2022-11-16 at 16.18.53.png" added.
Actual error
Comment (by Márton Salomváry):
The problem seems to be that the non-editable field is passed down as part
of `excludes`, which is right, we do not want to validate the value of the
non-editable field.
However this is not about validating the value of the non-editable field,
but conditionally validating the value of a *different* field, if the non-
editable field's value matches the condition.
The documentation on the semantics of `excludes` seems to confirm this:
https://docs.djangoproject.com/en/4.1/ref/models/instances/#django.db.models.Model.full_clean
"ModelForm uses this argument to exclude fields that aren’t present on
your form from being validated since any errors raised could not be
corrected by the user."
I'm a little confused however because I found a test that seems to
specifically verify this (but there is no explanation for the "why" or
"for what purpose").
https://github.com/django/django/blob/e14d08cd894e9d91cb5d9f44ba7532c1a223f458/tests/constraints/tests.py#L698-L703
I've also done a bit of Git archeology and found this conversation around
the same problem which ends with "That's a suitable workaround, but I feel
like it should not be necessary."
https://github.com/django/django/pull/14625#pullrequestreview-1074071130
Would a patch be accepted that makes the workaround unnecessary?
--
Ticket URL: <https://code.djangoproject.com/ticket/34166#comment:1>