Opened 8 years ago
Closed 7 years ago
#27710 closed Cleanup/optimization (fixed)
foreign key _id optimisation leads to incorrect descriptor value
Reported by: | Will Hardy | Owned by: | Paulo |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 1.10 |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Accepted | |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
A common optimisation (also recommended in the docs: https://docs.djangoproject.com/en/1.8/topics/db/optimization/#use-foreign-key-values-directly) is to use MyModel.relatedfield_id = 5
for setting a foreign key, when you want to avoid querying the database.
However, if the instance is then later used (accidentally or occasionally, that would defeat the point of the optimisation), the value of MyModel.relatedfield
can be incorrect. I think inefficient would be a better default than incorrect, because the mistake is subtle.
I imagine the ForwardManyToOneDescriptor
could check the primary key of the cache value being returned against the primary key on the model instance and if there is a mismatch, then the cache value should be deleted and a new query should be made.
>>> instance = MyModel(relatedfield_id=1) >>> print(instance.relatedfield.pk) 1 >>> instance.relatedfield_id = 2 >>> print(instance.relatedfield.pk) 1 >>> instance.save() >>> print(instance.relatedfield.pk) 1
Change History (4)
comment:1 by , 8 years ago
Component: | Uncategorized → Database layer (models, ORM) |
---|---|
Triage Stage: | Unreviewed → Accepted |
Type: | Uncategorized → Cleanup/optimization |
comment:2 by , 7 years ago
Owner: | changed from | to
---|---|
Status: | new → assigned |
I thought there might be another ticket where this was proposed and possibly rejected as "too magical", but I'm not going to do a search now. The idea seems reasonable at first glance.