Trouble with Django's QuerySet Caching When Using Prefetch Related in Large Datasets
I'm working on a project and hit a roadblock. I tried several approaches but none seem to work. I'm experiencing unexpected behavior with Django's ORM when retrieving related objects using `prefetch_related`. I have a large dataset, and I noticed that the related objects are being cached after the first query, which leads to outdated data being presented in subsequent accesses. Here's a simplified version of my code: ```python from django.db import models 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) # Fetching books with authors books = Book.objects.prefetch_related('author').all() for book in books: print(f'{book.title} by {book.author.name}') # Works fine initially # Now suppose I update an authorβs name some_author = Author.objects.first() some_author.name = 'Updated Name' some_author.save() # Accessing the same queryset again for book in books: print(f'{book.title} by {book.author.name}') # Still shows old author name ``` I expected the author's name to reflect the update on subsequent accesses, but it does not. I tried using `.all()` again on the `books` queryset after the update, but it still returns the cached versions of the authors. I've also checked the database and confirmed that the update was successful. Is there a way to refresh the related objects when using `prefetch_related`? Any suggestions on how to force the queryset to not cache the related objects, or is there a different approach I should be considering? I'm using Django 3.2.5 and PostgreSQL 13. Am I missing something obvious? Is there a better approach? My development environment is Ubuntu 20.04. Has anyone dealt with something similar?