1

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!

rabbid
  • 5,465
  • 7
  • 26
  • 37

1 Answers1

2

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/

MattH
  • 37,273
  • 11
  • 82
  • 84
  • Thanks for your reply. How would this code know what `'comments'` is? My Post model doesn't have any reference to Comments. Do I have to add that reference first into my Post model? – rabbid May 02 '11 at 09:36
  • If you have a reference to your comment model, like `comment_set`, use that. As you'd not posted your models, I was just guessing. – MattH May 02 '11 at 09:41
  • I've included my Post model code. I'm using Django's built-in comments model and I don't have any reference to it. I'm just following their [tutorial](http://docs.djangoproject.com/en/1.3/ref/contrib/comments/). I had previously implemented Disqus, but now am going to use Django's comments instead. So this is the first time I'm touching it. So how would I make a reference to the Comments model from my Post model? Thanks a lot! – rabbid May 02 '11 at 09:49