Django 中按评论数量过滤对象
如何按评论数过滤查询集,并按评论数降序排列?
我尝试执行类似 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')
我修复了我的模型和视图代码。他们现在工作得很好。
谢谢!
How do I filter queryset by the number of comments, and order by number of comments descending?
I tried to do something like Post.objects.filter(comment_count > 0).order_by('-comment_count')
but that didn't work or course.
Thanks!
My Post model:
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)
Edit:
Just added the following code
from django.contrib.contenttypes import generic
from django.contrib.comments.models import Comment
comments = generic.GenericRelation(Comment, object_id_field="object_pk")
And in my view:
post_list = Post.objects.annotate(comment_count=Count('comments')).filter(status=STATUS.ACCEPTED).filter(comment_count__gt=0).order_by('-comment_count')
I fixed my model and view code. They are now working fine.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用“注释”;像这样:
请参阅以下内容以获取更多信息:
http://docs.djangoproject.com/en/dev/topics/db/聚合/
Using 'annotations'; something like this:
See the following for more info:
http://docs.djangoproject.com/en/dev/topics/db/aggregation/