Opened 22 months ago
Closed 22 months ago
#34282 closed Cleanup/optimization (wontfix)
Optimize update_or_create when defaults is empty / False-y
Reported by: | Timothy Schilling | Owned by: | Timothy Schilling |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | dev |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
The defaults parameter to update_or_create
is used to change the values on a model instance after it's been fetched from the database. However, it's not required to pass anything in through defaults
. In these cases where defaults
is False-y, Django is performing an update on the model instance that shouldn't be changing any values. Instead the call to [object.save()](https://github.com/django/django/blob/stable/4.2.x/django/db/models/query.py#L971-L972) should be skipped.
The concern would be needing to check for fields that use something like auto_now
.
Thanks for this ticket. An empty set of
defaults
is always a subset ofconcrete_field_names
so the "else" branch is not reachable in this case. We could skip save() whenupdate_fields
is empty but this would be backward incompatible e.g. for users with database triggers. I'm not convinced it's worth changing, users who don't want to update any fields should useget_or_create()
instead. Hope that makes sense.