Opened 18 months ago
Last modified 16 months ago
#35575 closed New feature
Model.full_clean() does not recalculate GeneratedFields prior to validating model constraints — at Initial Version
| Reported by: | Mark Gensler | Owned by: | Mark Gensler |
|---|---|---|---|
| Component: | Database layer (models, ORM) | Version: | 5.0 |
| Severity: | Normal | Keywords: | generatedfield uniqueconstraint checkconstraint |
| Cc: | Mariusz Felisiak, Lily Foote, Simon Charette | Triage Stage: | Ready for checkin |
| Has patch: | yes | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
GeneratedFields on a model instance are not recalculated during Model.full_clean(). Therefore, if a GeneratedField is included in the *expressions or fields parameters of a UniqueConstraint or CheckConstraint in the instance's Model._meta, the values of the GeneratedField attribute are not recalculated prior to calling BaseConstraint.validate().
Instead, the model instance's GeneratedField attribute will return the value which corresponds to the most recent refresh of the instance from the database. If the instance is new and has not yet been saved, the following error is raised:
AttributeError: Cannot read a generated field from an unsaved model.
An IntegrityError is correctly raised when calling Model.save() if any constraints involving GeneratedFields are violated.
Instead, the GeneratedFields should have their values recalculated as part of Model.full_clean().
This ticket was raised after fixing the bug in #35560 with PR https://github.com/django/django/pull/18309.