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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With