如何按评论数量过滤查询集,并按评论数量下降排序?
我试图做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')
我修复了我的模型并查看了代码。他们现在工作正常。
谢谢!
答案 0 :(得分: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/