python - 将带有计算字段的 QuerySet 从键转换为一个或多个 json basead
问题描述
我正在尝试将 json 中的 QuerySet 转换为与 chartjs 一起使用,但我在转换时遇到了一些问题。例如:
_queryset = CheckOut.objects.filter(date_service__year = this_year).values_list('date_service__month').\
annotate(total=Sum('profit')).order_by('date_service__month')
dt = _queryset
如果打印这个变量“ dt ”,在模板中{{ dt }}
我打印了这个值
<QuerySet [(8, Decimal('300.00')), (9, Decimal('729.00'))]>
我如何分开:两个json中的月份和总计(来自注释),如下所示:
[8,9] <- month
[300, 729] <- total price
解决方案
由于数据是键/值对列表,您可以创建一个字典,然后使用keys()
andvalues()
方法提取值。使用 anOrderedDict
将确保订单被保留。
例如:
from collections import OrderedDict
_queryset = CheckOut.objects.filter(date_service__year = this_year).values_list('date_service__month').\
annotate(total=Sum('profit')).order_by('date_service__month')
dt = OrderedDict(_queryset) # Wrap queryset with an OrderedDict
extracted = {
'months': list(dt.keys()), # Extract the list of months
'totals': list(dt.values()) # Extract the list of totals
}
推荐阅读
- php - 如何在 php 中为 google drive api 添加多种 mime 类型
- c# - 有没有办法获取快捷链接的图标?
- c - 每次使用时对结构进行类型定义是否都会重新引入它?
- python - 转换日期类型
- php - 来自表单的mailchimp PHP API发送组
- javascript - 为什么我不能为变量 x 赋值
- java - 将 java 作为 java 应用程序运行与在服务器上运行的区别
- java - 比较两个 JSON 并显示我们更改了哪一列的活动?
- c++ - 使用动态索引访问参数包类型元组的单个元素
- html - 在 Vue3 中使用 InputMask PrimeVue 的问题