Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django order by count

Tags:

django

I have these models:

 class Project(models.Model):
   title=models.CharField(max_length=80)date_created=models.DateTimeField(auto_now_add=True)e)
    category = models.ForeignKey(Category)

class Category(models.Model):
    name = models.CharField(max_length=80)

And this in views:

cat_list = Category.objects.order_by(order_by)
for c in cat_list:
    count = Project.objects.filter(category__id=c.id).count()
    setattr(c, 'count', count)

How can I now order this by COUNT attribute?

like image 921
petros Avatar asked Apr 12 '14 17:04

petros


1 Answers

The proper way to do this is with annotation. This will reduce the amount of database queries to 1, and ordering will be a simple order_by function:

from django.db.models import Count

cat_list = Category.objects.annotate(count=Count('project_set__id')).order_by('count')
like image 166
knbk Avatar answered Oct 21 '22 15:10

knbk