'How to aggregate one column of django table based on another column

I have a table like below:

id    |    type   |    code
-------------------------------------

0.        5             2
1         6             6
2         8            16
3         4            11
4         5             4
5         2             2
6         4             1
7         10            6
8         9             2

All I need like output is a list of groupby on codes like here:

{ '2': [5,2,9], '6': [6, 10], '16': [8], '11':[4], ...}

I did this query but it's not doing the right query:

type_codes = [{ppd['code']:ppd['type_id']} for ppd in \
                    MyClass.objects \
                    .values('code', 'type_id')
                    .order_by()
               ]

Any help will be appericiated



Solution 1:[1]

You can try the following, iterating over the query result (using values_list):

data = MyClass.objects..values_list('code', 'type_id')
res = {}
for code, type in data:
    res[code] = [type] if code not in res.keys() else res[code] + [type]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marco