Django 中按评论数量过滤对象

发布于 2024-11-04 20:19:45 字数 1136 浏览 4 评论 0原文

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

我尝试执行类似 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撩心不撩汉 2024-11-11 20:19:45

使用“注释”;像这样:

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/聚合/

Using 'annotations'; something like this:

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

See the following for more info:
http://docs.djangoproject.com/en/dev/topics/db/aggregation/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文