开发者

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 C开发者_如何学JAVAomment(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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜