我需要从费用中使用ChartJs绘制图表。
这是我的观点
@login_required
def index(request):
truncate_month = connection.ops.date_trunc_sql('month', 'date_reg')
expense = Expense.objects.extra({'month': truncate_month}).values('month').annotate(Sum('total_amount'))
return render(request, 'home/index.html', {"expense": expense})
在我的模板上
{{ expense }}
它以下列格式显示数据:
[{
'month': '2015-12-01',
'total_amount__sum': 900.0
}, {
'month': '2016-01-01',
'total_amount__sum': 19334.0
}]
如何格式化该数据以与chartjs兼容?
ChartJs示例:
labels: ["January", "February", "March", "April", "May", "June", "July"], //Here the month
datasets: [{
label: "My First dataset",
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: [65, 59, 80, 81, 56, 55, 40] //here 'total_amount__sum'
},
...
答案 0 :(得分:1)
正如bryanph说使用Values_list,然后从ASCII更改引号,你需要在模板中转义它们。您可以使用安全过滤器。
Line in View: expenses = expense.values_list(' month',flat = True)
模板:
{{ expense|safe }}
答案 1 :(得分:0)
查看values_list:https://docs.djangoproject.com/es/1.9/ref/models/querysets/#values-list
这为您提供了值列表而不是字典。
答案 2 :(得分:0)
一种方法是挂钩underscore.js:
return render(request, 'home/index.html', json.dumps({"expense": expense}))
在模板中:
data = JSON.parse({{ expense|safe }});
var labels = _.pluck(data, 'month');
var data = _.pluck(data, 'total_amount__sum');