From 1058fc7023d04d07c22a5e667b6a446705119b14 Mon Sep 17 00:00:00 2001 From: Allen Jonathan David Date: Fri, 27 May 2022 17:43:12 +0530 Subject: [PATCH] Fixed #33191 -- Avoided clearing cached reference when saving child after parent. Thanks Barry Johnson for the report. --- django/db/models/base.py | 6 +++--- tests/many_to_one/tests.py | 10 ++++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/django/db/models/base.py b/django/db/models/base.py index a2f594041e..69224c0287 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -1100,9 +1100,9 @@ class Model(metaclass=ModelBase): "related object '%s'." % (operation_name, field.name) ) elif getattr(self, field.attname) in field.empty_values: - # Use pk from related object if it has been saved after - # an assignment. - setattr(self, field.attname, obj.pk) + # Set related object if it has been saved after an + # assignment. + setattr(self, field.name, obj) # If the relationship's pk/to_field was changed, clear the # cached relationship. if getattr(obj, field.target_field.attname) != getattr( diff --git a/tests/many_to_one/tests.py b/tests/many_to_one/tests.py index 2311834481..d9a8984c4c 100644 --- a/tests/many_to_one/tests.py +++ b/tests/many_to_one/tests.py @@ -654,6 +654,16 @@ class ManyToOneTests(TestCase): self.assertIsNot(c.parent, p) self.assertEqual(c.parent, p) + def test_save_parent_after_assign(self): + category = Category(name="cats") + record = Record(category=category) + category.save() + record.save() + category.name = "dogs" + with self.assertNumQueries(0): + self.assertEqual(category.id, record.category_id) + self.assertEqual(category.name, record.category.name) + def test_save_nullable_fk_after_parent(self): parent = Parent() child = ChildNullableParent(parent=parent)