django - How to group by and return values from each group? -


i have such table

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

how such items in view, mean group p_id , number values group

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

you can use values() , annotate() group, so:

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

after list of dicts pid_group this:

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

you can number value then:

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

hope helps.


Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -