我们可以首先查询每个国家和每个碎屑类型的
Student
S:
qs = Student.objects.values('country', 'clasType').annotate(
n=Count('pk')
).order_by('country', 'clasType')
现在我们可以使用
itertools.groupby
[Python-doc]
要在更紧凑的词典中将这些词典组合在一起,请执行以下操作:
from itertools import groupby
from operator import itemgetter
data = [
{'country': c, ** { li['clasType']: li['n'] for li in l } }
for c, l in groupby(qs, itemgetter('country'))
]
但我们仍然需要“修补”:一个国家可能还没有全部
clasType
S,我们可能想补充
0
对于这些,我们还需要计算总数。我们可以通过以下方式实现:
for subd in data:
total = 0
for ct, _ in CLASS_TYPE:
total += subd.setdefault(ct, 0)
subd['Total'] = total
现在
data
包含字典列表,每个字典
'country'
和
'Total'
密钥和每个
CLASS_TYPE
一把钥匙和
学生
为了那个
类类型
.