From 54e2e688e1cfbdb37dfa5dd3b3ffdf2af12b4423 Mon Sep 17 00:00:00 2001 From: Tim Graham Date: Fri, 20 Nov 2015 10:31:33 -0500 Subject: [PATCH] Fixed #25715 -- Fixed Model.refresh_from_db() with ForeignKey w/on_delete=SET_NULL. --- django/db/models/base.py | 2 +- docs/releases/1.8.7.txt | 3 +++ tests/basic/models.py | 1 + tests/basic/tests.py | 11 +++++++++++ 4 files changed, 16 insertions(+), 1 deletion(-) diff --git a/django/db/models/base.py b/django/db/models/base.py index 1dbf0e52e2b..149b0e5a42a 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -592,7 +592,7 @@ class Model(six.with_metaclass(ModelBase)): rel_instance = getattr(self, field.get_cache_name()) local_val = getattr(db_instance, field.attname) related_val = None if rel_instance is None else getattr(rel_instance, field.target_field.attname) - if local_val != related_val: + if local_val != related_val or (local_val is None and related_val is None): del self.__dict__[field.get_cache_name()] self._state.db = db_instance._state.db diff --git a/docs/releases/1.8.7.txt b/docs/releases/1.8.7.txt index acc82f15810..8ffae59b216 100644 --- a/docs/releases/1.8.7.txt +++ b/docs/releases/1.8.7.txt @@ -36,3 +36,6 @@ Bugfixes :class:`~django.contrib.postgres.fields.DateTimeRangeField` (:ticket:`24937`). * Fixed the exact lookup of ``ArrayField`` (:ticket:`25666`). + +* Fixed ``Model.refresh_from_db()`` updating of ``ForeignKey`` fields with + ``on_delete=models.SET_NULL`` (:ticket:`25715`). diff --git a/tests/basic/models.py b/tests/basic/models.py index 0e85087d323..91fbe7d6481 100644 --- a/tests/basic/models.py +++ b/tests/basic/models.py @@ -34,6 +34,7 @@ class SelfRef(models.Model): null=True, blank=True, related_name='+', ) + article = models.ForeignKey(Article, models.SET_NULL, null=True, blank=True) def __str__(self): # This method intentionally doesn't work for all cases - part diff --git a/tests/basic/tests.py b/tests/basic/tests.py index 84033da43e9..c67f78926f8 100644 --- a/tests/basic/tests.py +++ b/tests/basic/tests.py @@ -765,6 +765,17 @@ class ModelRefreshTests(TestCase): self.assertEqual(a2.pub_date, pub_date) self.assertEqual(a2._state.db, "default") + def test_refresh_fk_on_delete_set_null(self): + a = Article.objects.create( + headline='Parrot programs in Python', + pub_date=datetime(2005, 7, 28), + ) + s1 = SelfRef.objects.create(article=a) + a.delete() + s1.refresh_from_db() + self.assertIsNone(s1.article_id) + self.assertIsNone(s1.article) + def test_refresh_no_fields(self): a = Article.objects.create(pub_date=self._truncate_ms(datetime.now())) with self.assertNumQueries(0):