-1

I have such table

id p_id number 
1   1   12 
2   1   13
3   2   14
4   2   15

How to get such items in my view, i mean group by p_id and get number values from the group

for p_id 1 returns count 2 and 12,13
for p_id 2 returns count 2 and 14,15
4

1 回答 1

2

您可以使用values()andannotate()进行分组,因此:

from django.db.models import Count
pid_group = YourModel.objects.values('p_id').annotate(ncount=Count('number'))

之后你会得到一个pid_group这样的字典列表:

[{'p_id': 1, 'ncount': 2}, {'p_id': 2, 'ncount': 2}]

然后您可以轻松获取数值:

for pid in pid_group:
    number_values = YourModel.objects.filter(p_id=pid.get('p_id'))

希望能帮助到你。

于 2013-07-25T20:26:10.410 回答