Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django order by count of many to many object

I have a model :

class Category(models.Model):
    questions = models.ManyToManyField('Question', related_name="cat_question", blank=True)
    cat_name = models.CharField(max_length=50)
    cat_description = models.CharField(max_length=255)

    def __unicode__(self):
        return self.cat_name

and in my view I have :

top_categories = Category.objects.all()[:7].

I am passing it as context in the template. I want to sort the top categories by the number of questions in it like if A category has most question then it should be in top and if B has most question then B. Then second most and so on..

like top_categories = Category.objects.all().order_by(Count(question)

Any help ?

like image 467
varad Avatar asked Jan 31 '15 16:01

varad


1 Answers

Annotate Category objects with the number of questions and then order by this number in descend order:

from django.db.models import Count

top_categories = Category.objects.annotate(q_count=Count('questions')) \
                                 .order_by('-q_count')[:7]

and you can look on the example in the doc order-by, more examples for aggreagate cheat-sheet

like image 53
catavaran Avatar answered Sep 28 '22 12:09

catavaran