如何将分组查询集返回为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)
将value替换为values_list
self.model.objects.values_list('id').annotate(sum_amount=Sum('amount')).order_by('sum_amount')