Django QuerySet Caching Issue with Prefetch Related in Version 4.1.6
I'm prototyping a solution and I'm experiencing unexpected behavior when using `prefetch_related` with Django's ORM in version 4.1.6. My goal is to optimize database access for a list of authors and their related books, but I'm noticing that the queries are not being cached as I expected. After running the following code: ```python from django.db import models from django.shortcuts import render 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, related_name='books') def author_books(request): authors = Author.objects.prefetch_related('books').all() return render(request, 'authors.html', {'authors': authors}) ``` I expected that accessing `author.books.all()` would not hit the database again after the first access. However, I'm seeing multiple queries being executed in my logs. Here's the relevant part of the log output: ``` SELECT ... FROM app_author; SELECT ... FROM app_book WHERE author_id IN (...); SELECT ... FROM app_book WHERE author_id IN (...); ``` It seems like the code is causing multiple queries instead of leveraging the cached results from the prefetch. I've tried different variations of `prefetch_related` and even added `select_related` in various places, but none of those changes helped with the caching. Could this be an issue with how I'm iterating through the authors in my template? Iām using the following in my `authors.html`: ```html {% for author in authors %} <h2>{{ author.name }}</h2> <ul> {% for book in author.books.all %} <li>{{ book.title }}</li> {% endfor %} </ul> {% endfor %} ``` I also checked the documentation and confirmed that `prefetch_related` is indeed the correct method for this use case. Has anyone else encountered this issue or have insights on how to properly cache related objects in Django? For context: I'm using Python on Linux.