如何将 group by(values) 转换为 json - django
how to convert group by(values) to json - django
我正在尝试将按(django 中的值)分组的数据转换为 JsonResponse
,但它引发了此错误:
AttributeError: 'dict' object has no attribute 'f_type'
这是我加载json数据的函数
def load_cate(request):
lists = Room.objects.values('f_type','room_type', 'beds', 'balcon').annotate(total=Count('pk')).order_by('-total')
data = []
for i in lists.values():
item = {
'wc_type':i.f_type,
'room_type':i.room_type,
'beds':i.beds,
'balcon':i.balcon,
'total':i.total
}
data.append(item)
return JsonResponse({'success':True,'data':data})
我做错了什么吗?或者对于按值分组不同?!
提前致谢..
不需要遍历对象。您只需要将 QuerySet 转换为列表即可。
values() 将 return 一个不能在 JsonResponse 中 return 的 QuerySet 对象。所以只要转换成列表即可。
lists = Room.objects.values('f_type','room_type', 'beds', 'balcon').annotate(total=Count('pk')).order_by('-total')
lists = list(lists)
我正在尝试将按(django 中的值)分组的数据转换为 JsonResponse
,但它引发了此错误:
AttributeError: 'dict' object has no attribute 'f_type'
这是我加载json数据的函数
def load_cate(request):
lists = Room.objects.values('f_type','room_type', 'beds', 'balcon').annotate(total=Count('pk')).order_by('-total')
data = []
for i in lists.values():
item = {
'wc_type':i.f_type,
'room_type':i.room_type,
'beds':i.beds,
'balcon':i.balcon,
'total':i.total
}
data.append(item)
return JsonResponse({'success':True,'data':data})
我做错了什么吗?或者对于按值分组不同?! 提前致谢..
不需要遍历对象。您只需要将 QuerySet 转换为列表即可。 values() 将 return 一个不能在 JsonResponse 中 return 的 QuerySet 对象。所以只要转换成列表即可。
lists = Room.objects.values('f_type','room_type', 'beds', 'balcon').annotate(total=Count('pk')).order_by('-total')
lists = list(lists)