Django中如何实现分组查询


Django中如何实现分组查询

假如有如下查询:

Members.objects.all()

返回如下数据:

Eric, Salesman, X-Shop
Freddie, Manager, X2-Shop
Teddy, Salesman, X2-Shop
Sean, Manager, X2-Shop

实现分组查询如下:

from django.db.models import Count
Members.objects.values('designation').annotate(dcount=Count('designation'))

该查询和如下SQL查询相同:

SELECT designation, COUNT(designation) AS dcount
FROM members GROUP BY designation

输出结果如下:

[{'designation': 'Salesman', 'dcount': 2},
 {'designation': 'Manager', 'dcount': 2}]