diff options
| author | Bhuvnesh <bhuvnesh875@gmail.com> | 2022-11-07 12:36:30 +0530 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-11-07 08:06:30 +0100 |
| commit | 123b1d3fcf79f091573c40be6da7113a6ef35b62 (patch) | |
| tree | 84636f0bb2665b5e005d5f4c056c2be22e6ed619 | |
| parent | 5eab4d1924613a5506e517f157054b4852ae7dc2 (diff) | |
Fixed #34137 -- Made Model.refresh_from_db() clear cached generic relations.
Thanks Simon Charette for the implementation idea.
| -rw-r--r-- | django/db/models/base.py | 5 | ||||
| -rw-r--r-- | tests/contenttypes_tests/test_fields.py | 8 |
2 files changed, 13 insertions, 0 deletions
diff --git a/django/db/models/base.py b/django/db/models/base.py index 133adb6f3a..668b8cc221 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -737,6 +737,11 @@ class Model(AltersData, metaclass=ModelBase): 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): diff --git a/tests/contenttypes_tests/test_fields.py b/tests/contenttypes_tests/test_fields.py index 170b38d018..418669140b 100644 --- a/tests/contenttypes_tests/test_fields.py +++ b/tests/contenttypes_tests/test_fields.py @@ -43,6 +43,14 @@ class GenericForeignKeyTests(TestCase): 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): |
