[Answered ]-In Django, how do I choose data from one table and count from a corresponding table and output the same?

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.

Leave a comment