用于查找评论最多的前 3 篇帖子的 Django 查询

A Django query to find top 3 posts with maximum comments

如何找到评论最多的前 3 篇博文
这是我的模型:

 class BlogPost(models.Model):
    title = models.CharField(max_length=250)
    body = models.TextField()
class Comments(models.Model):
    post = models.ForeignKey('BlogPost', null=False, on_delete=models.CASCADE)
    comment = models.TextField()
from django.db.models import Count

BlogPost.post_set.values('comment').annotate(comment_count=Count('comment'))

试试这个并检查是否会 return 一些东西。

编辑 1:

试试这个

posts = BlogPost.objects.all()
relation = []
for post in posts:
    post_number = len(list(post.post_set.all()))
    relation.append({'post': post, 'post_number': post_number})

这将为您提供前 3 个 posts 以及按 posts.

分组的评论数 (dcount)
from django.db.models import Count

Comments.objects.values('post').annotate(dcount=Count('id')).order_by('-dcount')[:3]

我强烈建议不要使用 .values(…) [Django-doc],因为那时你不再使用 Post 对象,而是使用字典。您可以使用:

from django.db.models import Count

BlogPost.objects.alias(
    <strong>num_comments=Count('Comments')</strong>
).order_by(<strong>'-num_comments'</strong>)<strong>[:3]</strong>

Note: normally a Django model is given a singular name, so Comment instead of Comments.


Note: Specifying null=False [Django-doc] is not necessary: fields are by default not NULLable.