Arpit Rai
Arpit Rai

Reputation: 1027

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

I have two models as described below:

class Post(models.Model):
  title = models.CharField(max_length=60)
  details = models.TextField()

class Comment(models.Model):
  blog_post = models.ForeignKey(Post)
  name = models.CharField(max_length=40)
  comment = models.TextField()

I want to write a view that shows all entries from Post and the corresponding number of comments for each post.

I know I can get the comments count by doing: Comment.objects.filter(blog_post__title__icontains='xxx').count()

I just want to output a HTML page where all posts show up and each post should have a corresponding comment count (just the count, not the actual comment entries/data). How do I do this? How do I pass the list of posts and the corresponding comment count for each post to the template?

Upvotes: 1

Views: 216

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

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.

Upvotes: 2

Related Questions