Using a typical set of Post & Comment models, where Comment has a foreign key to Post, I couldn't figure out how to do this with just a single query in Django. Using prefetch_related, the 2-query version is pretty straightforward:
from django.db.models import Count, Prefetch
from myproject.models import Post, Comment
# This will fetch the 3 posts first and then the comments for those posts
query = Post.objects.prefetch_related(
Prefetch("comments", queryset=Comment.objects.annotate(Count("votes")))
)
posts = query[:3]
How would you reduce this to one query using the Django ORM?