Django 4.0 - Unexpected QuerySet Caching Behavior with Prefetch Related on Many-to-One Relationships
I'm relatively new to this, so bear with me. I'm relatively new to this, so bear with me. I'm working on a Django 4.0 application and encountered an unexpected behavior when using `prefetch_related` with a many-to-one relationship. I have two models, `Author` and `Book`, where each book is linked to an author. I'm trying to optimize my queries, so I'm prefetching the authors for the books, but it seems that the QuerySet is caching the results in a way that I didn't expect. Here's a simplified version of my models: ```python class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) ``` In my view, I want to retrieve books along with their authors: ```python from .models import Book books = Book.objects.prefetch_related('author').all() ``` When I iterate over the books and print their authors, everything works fine: ```python for book in books: print(book.title, book.author.name) ``` However, when I try to filter the books after fetching them: ```python filtered_books = [book for book in books if 'Python' in book.title] ``` I notice that the author names are not being fetched fresh for these filtered books. Instead, it seems to be using the cached authors from the previous iteration. I expected that filtering would trigger fresh queries to the database instead of relying on cached values. This is causing some unexpected behavior because if I change an author's name after fetching the books but before filtering, the output does not reflect that change since the author names are cached. I've tried using `list()` on the QuerySet before filtering, but that didn't solve the issue either. How can I force Django to refresh the related data after filtering? Is there a way to avoid this caching issue altogether? Any insights would be greatly appreciated! For context: I'm using Python on macOS. What am I doing wrong? I'm working on a CLI tool that needs to handle this.