2👍
✅
You use aggregation. When you’re getting your list of posts, you tell Django you want to count the related Comments at the same time:
from django.db.models import Count
posts = Post.objects.all().annotate(comment_count=Count('comment'))
Now each post in the posts
queryset has a comment_count
attribute, which is the number of related comments.
Source:stackexchange.com