Django按计数排序

时间:2014-04-12 17:27:25

标签: django

我有这些模特:

 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)

这在观点中:

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)

我现在如何通过COUNT属性订购?

1 个答案:

答案 0 :(得分:4)

执行此操作的正确方法是使用annotation。这会将数据库查询量减少到1,并且排序将是一个简单的order_by函数:

from django.db.models import Count

cat_list = Category.objects.annotate(count=Count('project_set__id')).order_by('count')
相关问题