﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
29625	Make Model.refresh_from_db()  clear prefetch related caches	Ming Qin	Ming Qin	"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."	Cleanup/optimization	closed	Database layer (models, ORM)	dev	Normal	fixed	prefetch_related, _prefetched_objects_cache		Accepted	1	0	0	0	0	0
