Opened 11 months ago

Closed 13 days 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 Changed 11 months ago by Tim Graham

Component: UncategorizedDatabase layer (models, ORM)
Triage Stage: UnreviewedAccepted
Type: UncategorizedCleanup/optimization

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.

comment:2 Changed 2 months ago by Paulo

Owner: changed from nobody to Paulo
Status: newassigned

comment:4 Changed 13 days ago by Tim Graham <timograham@…>

Resolution: fixed
Status: assignedclosed

In ee493061:

Fixed #27710 -- Made Model.save() invalidate cached, stale relations after a primary key assignment.

Note: See TracTickets for help on using tickets.
Back to Top