diff --git a/django/db/models/base.py b/django/db/models/base.py
index f88690f225..3a54d0fc08 100644
a
|
b
|
class Model(metaclass=ModelBase):
|
659 | 659 | # been assigned and there's no need to worry about this check. |
660 | 660 | if field.is_relation and field.is_cached(self): |
661 | 661 | obj = getattr(self, field.name, None) |
| 662 | obj_pk = getattr(self, field.attname, None) |
662 | 663 | # A pk may have been assigned manually to a model instance not |
663 | 664 | # saved to the database (or auto-generated in a case like |
664 | 665 | # UUIDField), but we allow the save to proceed and rely on the |
665 | 666 | # database to raise an IntegrityError if applicable. If |
666 | 667 | # constraints aren't supported by the database, there's the |
667 | 668 | # unavoidable risk of data corruption. |
668 | | if obj and obj.pk is None: |
| 669 | if obj and (obj.pk is None or obj_pk is None): |
669 | 670 | # Remove the object from a related instance cache. |
670 | 671 | if not field.remote_field.multiple: |
671 | 672 | field.remote_field.delete_cached_value(obj) |
… |
… |
class Model(metaclass=ModelBase):
|
675 | 676 | ) |
676 | 677 | # If the relationship's pk was changed, clear the cached |
677 | 678 | # relationship. |
678 | | if obj and obj.pk != getattr(self, field.attname): |
| 679 | if obj and obj.pk != obj_pk: |
679 | 680 | field.delete_cached_value(self) |
680 | 681 | |
681 | 682 | using = using or router.db_for_write(self.__class__, instance=self) |
diff --git a/tests/many_to_one/tests.py b/tests/many_to_one/tests.py
index a2ff587ab3..7b0bb367e9 100644
a
|
b
|
class ManyToOneTests(TestCase):
|
522 | 522 | self.assertIsNot(c.parent, p) |
523 | 523 | self.assertEqual(c.parent, p) |
524 | 524 | |
| 525 | def test_unsaved_object(self): |
| 526 | msg = "save() prohibited to prevent data loss due to unsaved related object 'parent'." |
| 527 | child = Child() |
| 528 | child.parent = Parent() |
| 529 | child.parent.save() |
| 530 | with self.assertRaisesMessage(ValueError, msg): |
| 531 | child.save() |
| 532 | |
525 | 533 | def test_fk_to_bigautofield(self): |
526 | 534 | ch = City.objects.create(name='Chicago') |
527 | 535 | District.objects.create(city=ch, name='Far South') |