I have a situation something like this (the actual code is bound up in a template, and omitted for brevity).
threads = Thread.objects.all()
for thread in threads:
threads = Thread.objects.prefetch_related('comments').prefetch_related('upvotes')
You're right, it's wasteful to fetch all that data from the database if all you want to do is get the count. I suggest annotation:
threads = (Thread.objects.annotate(Count('comments', distinct=True)) .annotate(Count('upvotes', distinct=True))) for thread in threads: print(thread.comments__count) print(thread.upvotes__count)
See the annotation documentation for more information.