Skip to content

Commit

Permalink
Fixed #27846 -- Made Model.refresh_from_db() clear cached relations.
Browse files Browse the repository at this point in the history
  • Loading branch information
czpython authored and timgraham committed Oct 12, 2017
1 parent df0aebc commit a7b5ad8
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
6 changes: 6 additions & 0 deletions django/db/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -627,6 +627,12 @@ def refresh_from_db(self, using=None, fields=None):
related_val = None if rel_instance is None else getattr(rel_instance, field.target_field.attname)
if local_val != related_val or (local_val is None and related_val is None):
field.delete_cached_value(self)

# Clear cached relations.
for field in self._meta.related_objects:
if field.is_cached(self):
field.delete_cached_value(self)

self._state.db = db_instance._state.db

def serializable_value(self, field_name):
Expand Down
4 changes: 4 additions & 0 deletions tests/basic/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ def __str__(self):
return self.headline


class FeaturedArticle(models.Model):
article = models.OneToOneField(Article, models.CASCADE, related_name='featured')


class ArticleSelectOnSave(Article):
class Meta:
proxy = True
Expand Down
13 changes: 12 additions & 1 deletion tests/basic/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
)
from django.utils.translation import gettext_lazy

from .models import Article, ArticleSelectOnSave, SelfRef
from .models import Article, ArticleSelectOnSave, FeaturedArticle, SelfRef


class ModelInstanceCreationTests(TestCase):
Expand Down Expand Up @@ -711,3 +711,14 @@ def test_refresh_no_fields(self):
a = Article.objects.create(pub_date=datetime.now())
with self.assertNumQueries(0):
a.refresh_from_db(fields=[])

def test_refresh_clears_reverse_related(self):
"""refresh_from_db() clear cached reverse relations."""
article = Article.objects.create(
headline='Parrot programs in Python',
pub_date=datetime(2005, 7, 28),
)
self.assertFalse(hasattr(article, 'featured'))
FeaturedArticle.objects.create(article_id=article.pk)
article.refresh_from_db()
self.assertTrue(hasattr(article, 'featured'))

0 comments on commit a7b5ad8

Please sign in to comment.