首页 > 解决方案 > 将带有计算字段的 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

标签: pythondjangodjango-admin

解决方案


由于数据是键/值对列表,您可以创建一个字典,然后使用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
}

推荐阅读