Django QuerySet Caching guide - Unwanted Behavior with Annotate and Prefetch Related
Can someone help me understand I'm working with a peculiar scenario with Django's ORM when using `annotate()` and `prefetch_related()`... I have a model `Book` that has a foreign key to another model `Author`. The question arises when I try to annotate a count of books per author while prefetching related authors. It seems like the queries are being cached incorrectly, leading to unexpected results in my template. Here's an example of my models: ```python class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, related_name='books', on_delete=models.CASCADE) ``` In my view, I'm trying to do the following: ```python from django.db.models import Count def author_list(request): authors = Author.objects.annotate(book_count=Count('books')).prefetch_related('books') return render(request, 'author_list.html', {'authors': authors}) ``` When I loop through the `authors` in my template: ```html {% for author in authors %} <h2>{{ author.name }}</h2> <p>Books Count: {{ author.book_count }}</p> <ul> {% for book in author.books.all %} <li>{{ book.title }}</li> {% endfor %} </ul> {% endfor %} ``` The output is correct for the book count, but when I add a new `Book` through the Django admin and then refresh the page, the `book_count` reflects the old count (before adding the new book). It seems like the annotation is not being recalculated after the database change. The version of Django I'm using is 3.2.5. I've tried clearing the cache and re-evaluating the query, but the question continues. Would appreciate any insights on how to force the annotation to refresh or if there's a better approach to handle this scenario. Also, I checked the SQL queries being generated using `connection.queries` and it seems like the annotation query is only executed once, even after a database modification. Thanks in advance for your help! My development environment is Ubuntu. I'm working on a mobile app that needs to handle this. Could this be a known issue?