#29625: Expose RelatedManager._remove_prefetched_objects as public method
-------------------------------------+-------------------------------------
Reporter: QinMing | Owner: nobody
Type: | Status: new
Cleanup/optimization |
Component: Database | Version: master
layer (models, ORM) | Keywords: prefetch_related,
Severity: Normal | _prefetched_objects_cache
Triage Stage: | Has patch: 1
Unreviewed |
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 1
UI/UX: 0 |
-------------------------------------+-------------------------------------
The method currently starts with underscore, meaning it's not supposed to
be accessed from the outside. But I find that sometimes I have to use this
method to clear the cache, otherwise the outdated data will be returned.
The following test shows a scenario where this method is useful.
{{{
#!python
def setUpTestData(cls):
cls.book1 = Book.objects.create(title='Les confessions Volume I')
cls.book2 = Book.objects.create(title='Candide')
cls.author1 = AuthorWithAge.objects.create(name='Rousseau',
first_book=cls.book1, age=70)
cls.author2 = AuthorWithAge.objects.create(name='Voltaire',
first_book=cls.book2, age=65)
cls.book1.authors.add(cls.author1)
cls.book2.authors.add(cls.author2)
FavoriteAuthors.objects.create(author=cls.author1,
likes_author=cls.author2)
def test_remove_prefetched_objects(self):
"""
Test RelatedManager._remove_prefetched_objects method
"""
books = Book.objects.prefetch_related('first_time_authors')
book1 = books.get(title='Les confessions Volume I')
book2 = books.get(title='Candide')
# Update the related object - author1. So book1 has no first-time
author now, but still has one in cache
author1 = book1.authors.first()
author1.first_book = book2
author1.save()
self.assertQuerysetEqual(
book1.first_time_authors.all(), ['<Author: Rousseau>'],
msg="Expect the outdated cached data")
# Now clear the prefetched objects
book1.first_time_authors._remove_prefetched_objects()
self.assertQuerysetEqual(
book1.first_time_authors.all(), [], msg="Expect the fresh data
from database")
}}}
I'm working on opening a PR to add the above test case, and create an
alias of that method with no underscore. Let me know what you think.
--
Ticket URL: <https://code.djangoproject.com/ticket/29625>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/050.e3f6a93fb6a38c1c966b653b67d17348%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.