0

Very simple... I am using Django 1.4.1, and need to order a queryset by the inverse of the number of comments on it. I am using the Django comment framework, and have attempted to use the .annotate(comment_count = Count('comment') structure recommended in other answers... I get 'comment' doesn't resolve to a field error.

I've also tried the 0.3.1 version of django-generic-aggregate, which throws a database error, so that's out.

Photo.objects.filter(galleries=gallery).annotate(comment_count=Count('comments')).order_by('-comment_count')[(page-1)*RESULTS_PER_PAGE:page*RESULTS_PER_PAGE]

Any suggestions?

  • Please update your question with the relevant contents of the `Photo` model – Austin Phillips Mar 11 '13 at 02:59
  • I'm confused... The comments system is built into Django. It attaches to any model. The Photo model structure itself is irrelevant, I could as well be trying to order Widgets by comment count. – William Maness Mar 11 '13 at 11:07
  • Ignore my comment. I didn't realize the commenting app uses a `GenericForeignKey` and so doesn't require an explicit reference relating your `Photo` model. You might find that what you're trying to do isn't currently possible. See [here](https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations-and-aggregation) – Austin Phillips Mar 11 '13 at 11:52
  • Hi Austin, Yeah, I saw that it's not supported natively. I'm pretty sure that is what django-generic-aggregate is supposed to fix. I'm looking for a way to accomplish the task, even if it's not pretty. Thanks! – William Maness Mar 11 '13 at 14:06

1 Answers1

0

Put the function under Photo model

class Photo(models.Model):
    .........

    def orders(self):
        //filter first the highest count of comments
        aggregate = Photo.objects.aggregate(comment_count=Count('comments'))
        return aggregate['comment_count'] + 1

Then you can call it like this in view:

comments = Photo.objects.filter(galleries=gallery).orders()
catherine
  • 22,492
  • 12
  • 61
  • 85
  • Thanks for the answer Catherine! I'm confused though, I'm trying to order my queryset by the comment_count... Will this method do that? (is orders a magic method name?) – William Maness Mar 11 '13 at 11:09
  • I have a badge model and I need to get the ranking of the users based on the points so I did that way and it works. I don't know in your side, just try. If not working we will try another until your problem is solve :) – catherine Mar 11 '13 at 11:13