开发者

filter objects by number of comments in Django

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开发者_JS百科(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!


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜