Fixed #33191 -- Avoided clearing cached reference when saving child after parent.

Thanks Barry Johnson for the report.
This commit is contained in:
Allen Jonathan David 2022-05-27 17:43:12 +05:30 committed by Mariusz Felisiak
parent f1e0fc645b
commit 1058fc7023
2 changed files with 13 additions and 3 deletions

View File

@ -1100,9 +1100,9 @@ class Model(metaclass=ModelBase):
"related object '%s'." % (operation_name, field.name) "related object '%s'." % (operation_name, field.name)
) )
elif getattr(self, field.attname) in field.empty_values: elif getattr(self, field.attname) in field.empty_values:
# Use pk from related object if it has been saved after # Set related object if it has been saved after an
# an assignment. # assignment.
setattr(self, field.attname, obj.pk) setattr(self, field.name, obj)
# If the relationship's pk/to_field was changed, clear the # If the relationship's pk/to_field was changed, clear the
# cached relationship. # cached relationship.
if getattr(obj, field.target_field.attname) != getattr( if getattr(obj, field.target_field.attname) != getattr(

View File

@ -654,6 +654,16 @@ class ManyToOneTests(TestCase):
self.assertIsNot(c.parent, p) self.assertIsNot(c.parent, p)
self.assertEqual(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): def test_save_nullable_fk_after_parent(self):
parent = Parent() parent = Parent()
child = ChildNullableParent(parent=parent) child = ChildNullableParent(parent=parent)