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)