Django 4.1: implementing Using Prefetch Related with Generic Foreign Keys
I'm working through a tutorial and I've been struggling with this for a few days now and could really use some help. I'm currently working on a Django 4.1 application where I'm trying to optimize my queries using `prefetch_related`, but I'm running into issues with generic foreign keys. I have a `Comment` model that can relate to either `Post` or `Photo` models using a generic foreign key. When I try to prefetch both related models, I get the behavior `want to prefetch 'content_type' on a generic relation`. Here are the relevant models: ```python from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() class Photo(models.Model): image = models.ImageField(upload_to='photos/') class Comment(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') text = models.TextField() ``` I attempted to load the comments for both posts and photos like this: ```python posts = Post.objects.prefetch_related('comment_set').all() photos = Photo.objects.prefetch_related('comment_set').all() ``` However, this gives me the aforementioned behavior. Iβve also tried: ```python posts = Post.objects.prefetch_related('comment_set').annotate(num_comments=models.Count('comment')) photos = Photo.objects.prefetch_related('comment_set').annotate(num_comments=models.Count('comment')) ``` But it doesnβt seem to solve the prefetched data not working as expected. When I access `post.comment_set.all()` or `photo.comment_set.all()`, I still hit the database for each call. Any ideas on how to correctly use `prefetch_related` with generic foreign keys? Am I missing something crucial in the configuration, or is there a fundamental limitation I need to be aware of? I'm using Python LTS in this project. Thanks for your help in advance!