Skip to content

Commit

Permalink
Fixed #34137 -- Made Model.refresh_from_db() clear cached generic rel…
Browse files Browse the repository at this point in the history
…ations.

Thanks Simon Charette for the implementation idea.
  • Loading branch information
DevilsAutumn authored Nov 7, 2022
1 parent 5eab4d1 commit 123b1d3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
5 changes: 5 additions & 0 deletions django/db/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -737,6 +737,11 @@ def refresh_from_db(self, using=None, fields=None):
if field.is_cached(self):
field.delete_cached_value(self)

# Clear cached private relations.
for field in self._meta.private_fields:
if field.is_relation and field.is_cached(self):
field.delete_cached_value(self)

self._state.db = db_instance._state.db

async def arefresh_from_db(self, using=None, fields=None):
Expand Down
8 changes: 8 additions & 0 deletions tests/contenttypes_tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ def test_get_object_cache_respects_deleted_objects(self):
self.assertIsNone(post.parent)
self.assertIsNone(post.parent)

def test_clear_cached_generic_relation(self):
question = Question.objects.create(text="What is your name?")
answer = Answer.objects.create(text="Answer", question=question)
old_entity = answer.question
answer.refresh_from_db()
new_entity = answer.question
self.assertIsNot(old_entity, new_entity)


class GenericRelationTests(TestCase):
def test_value_to_string(self):
Expand Down

0 comments on commit 123b1d3

Please sign in to comment.