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?
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')
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