1

如何按评论数量过滤查询集,并按评论数量降序排列?

我试图做类似的事情,Post.objects.filter(comment_count > 0).order_by('-comment_count')但没有奏效或课程。

谢谢!

我的帖子模型:

class Post(models.Model):
 nickname = models.CharField(max_length=200, default=u'anonymous')
 body = models.TextField()
 pub_date = models.DateTimeField('Date Published', auto_now_add=True)
 up_date = models.DateTimeField('Date Updated', auto_now=True)
 category = models.ForeignKey(Category, related_name='post_category')
 counter = models.IntegerField(default=0)
 status = models.IntegerField(choices=POST_STATUS, default=0)
 votes = models.IntegerField('Votes', default=0)

编辑:

刚刚添加了以下代码

from django.contrib.contenttypes import generic
from django.contrib.comments.models import Comment

comments = generic.GenericRelation(Comment, object_id_field="object_pk")

在我看来:

post_list = Post.objects.annotate(comment_count=Count('comments')).filter(status=STATUS.ACCEPTED).filter(comment_count__gt=0).order_by('-comment_count')

我修复了我的模型并查看代码。他们现在工作正常。

谢谢!

4

1 回答 1

2

使用“注释”;像这样的东西:

from django.db.models import Count
Post.objects.annotate(comment_count=Count('comments')).filter(comment_count__gt=0).order_by('-comment_count')

有关更多信息,请参阅以下内容:http: //docs.djangoproject.com/en/dev/topics/db/aggregation/

于 2011-05-02T09:28:36.383 回答