﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
27710	foreign key _id optimisation leads to incorrect descriptor value	Will Hardy	Paulo	"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
}}}"	Cleanup/optimization	closed	Database layer (models, ORM)	1.10	Normal	fixed			Accepted	1	0	0	0	0	0
