如何将分组的查询集作为json返回?
我试过
def get(self, request, *args, **kwargs):
q = self.model.objects.values('id').annotate(sum_amount=Sum('amount')).order_by('sum_amount')
json_dict = [obj for obj in q]
return self.render_json_response(json_dict)
但结果是
[
{
"id": 13,
"sum_amount": "200.00"
},
{
"id": 3,
"sum_amount": "300.00"
},
]
输出应该是一个数组:
[
[
13, "200.00"
],
[
3, "300.00"
],
]
似乎与
一起使用def get(self, request, *args, **kwargs):
q = self.model.objects.all()
json_dict = [[obj.id, obj.amount] for obj in q]
return self.render_json_response(json_dict)
但它没有分组。
答案 0 :(得分:0)
用values_list替换值
self.model.objects.values_list('id').annotate(sum_amount=Sum('amount')).order_by('sum_amount')