Refs #28723 -- Fixed stale prefetch_related cache after add/remove.

Regression in 514b2c989a.
This commit is contained in:
Jon Dufresne 2018-02-05 08:02:57 -08:00 committed by Tim Graham
parent 16ee53d7bb
commit 8b21878357
3 changed files with 18 additions and 2 deletions

View File

@ -575,7 +575,7 @@ def create_reverse_many_to_one_manager(superclass, rel):
def _remove_prefetched_objects(self):
try:
self.instance._prefetched_objects_cache.pop(self.field.related_query_name())
self.instance._prefetched_objects_cache.pop(self.field.remote_field.get_cache_name())
except (AttributeError, KeyError):
pass # nothing to clear from cache

View File

@ -86,7 +86,8 @@ class Reader(models.Model):
class BookReview(models.Model):
book = models.ForeignKey(BookWithYear, models.CASCADE)
# Intentionally does not have a related name.
book = models.ForeignKey(BookWithYear, models.CASCADE, null=True)
notes = models.TextField(null=True, blank=True)

View File

@ -1415,6 +1415,21 @@ class DirectPrefechedObjectCacheReuseTests(TestCase):
with self.assertNumQueries(0):
prefetch_related_objects([bookwithyear1], 'bookreview_set')
def test_add_clears_prefetched_objects(self):
bookwithyear = BookWithYear.objects.get(pk=self.bookwithyear1.pk)
prefetch_related_objects([bookwithyear], 'bookreview_set')
self.assertCountEqual(bookwithyear.bookreview_set.all(), [self.bookreview1])
new_review = BookReview.objects.create()
bookwithyear.bookreview_set.add(new_review)
self.assertCountEqual(bookwithyear.bookreview_set.all(), [self.bookreview1, new_review])
def test_remove_clears_prefetched_objects(self):
bookwithyear = BookWithYear.objects.get(pk=self.bookwithyear1.pk)
prefetch_related_objects([bookwithyear], 'bookreview_set')
self.assertCountEqual(bookwithyear.bookreview_set.all(), [self.bookreview1])
bookwithyear.bookreview_set.remove(self.bookreview1)
self.assertCountEqual(bookwithyear.bookreview_set.all(), [])
class ReadPrefetchedObjectsCacheTests(TestCase):
@classmethod