Ticket #29085: patch.diff

File patch.diff, 2.4 KB (added by Jonas Haag, 7 years ago)
  • django/db/models/base.py

    diff --git a/django/db/models/base.py b/django/db/models/base.py
    index f88690f225..3a54d0fc08 100644
    a b class Model(metaclass=ModelBase):  
    659659            # been assigned and there's no need to worry about this check.
    660660            if field.is_relation and field.is_cached(self):
    661661                obj = getattr(self, field.name, None)
     662                obj_pk = getattr(self, field.attname, None)
    662663                # A pk may have been assigned manually to a model instance not
    663664                # saved to the database (or auto-generated in a case like
    664665                # UUIDField), but we allow the save to proceed and rely on the
    665666                # database to raise an IntegrityError if applicable. If
    666667                # constraints aren't supported by the database, there's the
    667668                # 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):
    669670                    # Remove the object from a related instance cache.
    670671                    if not field.remote_field.multiple:
    671672                        field.remote_field.delete_cached_value(obj)
    class Model(metaclass=ModelBase):  
    675676                    )
    676677                # If the relationship's pk was changed, clear the cached
    677678                # relationship.
    678                 if obj and obj.pk != getattr(self, field.attname):
     679                if obj and obj.pk != obj_pk:
    679680                    field.delete_cached_value(self)
    680681
    681682        using = using or router.db_for_write(self.__class__, instance=self)
  • tests/many_to_one/tests.py

    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):  
    522522        self.assertIsNot(c.parent, p)
    523523        self.assertEqual(c.parent, p)
    524524
     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
    525533    def test_fk_to_bigautofield(self):
    526534        ch = City.objects.create(name='Chicago')
    527535        District.objects.create(city=ch, name='Far South')
Back to Top