[1.8.x] Fixed #25715 -- Fixed Model.refresh_from_db() with ForeignKey w/on_delete=SET_NULL.

Backport of 54e2e688e1 from master
This commit is contained in:
Tim Graham 2015-11-20 10:31:33 -05:00
parent bc8bae0ba9
commit 2179e5a2bc
4 changed files with 16 additions and 1 deletions

View File

@ -630,7 +630,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.related_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

View File

@ -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`).

View File

@ -30,6 +30,7 @@ class ArticleSelectOnSave(Article):
class SelfRef(models.Model):
selfref = models.ForeignKey('self', null=True, blank=True,
related_name='+')
article = models.ForeignKey(Article, on_delete=models.SET_NULL, null=True, blank=True)
def __str__(self):
# This method intentionally doesn't work for all cases - part

View File

@ -767,6 +767,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):