[2.1.x] Fixed #29896 -- Fixed incorrect Model.save() cache relation clearing for foreign keys that use to_field.

Regression in ee49306176.
Backport of f77fc56c96 from master.
This commit is contained in:
Tim Graham 2018-10-28 22:54:02 -04:00
parent 69603b3e71
commit 0f02d71995
3 changed files with 12 additions and 3 deletions

View File

@ -669,9 +669,9 @@ class Model(metaclass=ModelBase):
"save() prohibited to prevent data loss due to "
"unsaved related object '%s'." % field.name
)
# If the relationship's pk was changed, clear the cached
# relationship.
if obj and obj.pk != getattr(self, field.attname):
# If the relationship's pk/to_field was changed, clear the
# cached relationship.
if obj and getattr(obj, field.target_field.attname) != getattr(self, field.attname):
field.delete_cached_value(self)
using = using or router.db_for_write(self.__class__, instance=self)

View File

@ -17,3 +17,6 @@ Bugfixes
* Fixed a regression in Django 2.0 where test databases aren't reused with
``manage.py test --keepdb`` on MySQL (:ticket:`29827`).
* Fixed a regression where cached foreign keys that use ``to_field`` were
incorrectly cleared in ``Model.save()`` (:ticket:`29896`).

View File

@ -666,3 +666,9 @@ class ManyToOneTests(TestCase):
self.a.reporter_id = self.r2.pk
self.a.save()
self.assertEqual(self.a.reporter, self.r2)
def test_cached_foreign_key_with_to_field_not_cleared_by_save(self):
parent = Parent.objects.create(name='a')
child = ToFieldChild.objects.create(parent=parent)
with self.assertNumQueries(0):
self.assertIs(child.parent, parent)