如何根据另一列聚合django table的一列

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

我有一个 table 如下所示:

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

我只需要像输出这样的代码的 groupby 列表:

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

我做了这个查询,但它没有做正确的查询:

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

任何帮助都会得到回报

您可以尝试以下操作,遍历查询结果(使用 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]