#34296 closed Bug (duplicate)
Formset validation does not consider UniqueConstraint with F() expressions.
Reported by: | Jannis Vajen | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | dev |
Severity: | Normal | Keywords: | formset, constraints |
Cc: | Triage Stage: | Accepted | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
When saving a formset with data that violates the model's UniqueConstraint()
, no form validation error is reported during formset.is_valid()
. Instead an IntegrityError is raised during formset.save()
. This only happens with the rather new UniqueConstraint()
, the older method of using Meta.unique_together
doesn't suffer from this.
Attachments (1)
Change History (5)
by , 22 months ago
Attachment: | unique_constraint.diff added |
---|
comment:1 by , 22 months ago
Version: | 4.1 → dev |
---|
comment:2 by , 22 months ago
Resolution: | → duplicate |
---|---|
Status: | new → closed |
Summary: | Formset validation does not consider models.UniqueConstraint → Formset validation does not consider UniqueConstraint with F() expressions. |
Triage Stage: | Unreviewed → Accepted |
comment:3 by , 22 months ago
As a workaround you can use fields
instead of *expressions
, e.g.
UniqueConstraint(fields=["poet", "name"], name="unique_together_poet_name")
comment:4 by , 22 months ago
Thank you, Mariusz. Using fields=[]
works as expected.
If UniqueConstraints
with expressions
are excluded from validation on purpose, I wonder if this should be mentioned in the docs. It seems to me that the admonition you added in #33335
Validation of Constraints
In general constraints are not checked during full_clean(), and do not raise ValidationErrors. Rather you’ll get a database integrity error on save(). UniqueConstraints without a condition (i.e. non-partial unique constraints) and expressions (i.e. non-functional unique constraints) are different in this regard, in that they leverage the existing validate_unique() logic, and thus enable two-stage validation. In addition to IntegrityError on save(), ValidationError is also raised during model validation when the UniqueConstraint is violated.
still fully applies in 4.1, 4.2, and dev and should not have been removed during #30581
Validation of Constraints
Constraints are checked during the model validation.
Do you agree, or am I overlooking something?
Test to reproduce the issue