Python 使用Django将数据传递到Google图表

Python 使用Django将数据传递到Google图表,python,mysql,django,Python,Mysql,Django,有人问过这个问题,但没有这样回答 在myview.py中,我从MySQL中提取了数据,例如数组: (Decimal('13'), Decimal('6'), Decimal('13')) (Decimal('207'), Decimal('18'), Decimal('129')) (Decimal('301'), Decimal('38'), Decimal('193')) (Decimal('204'), Decimal('32'), Decimal('150')) (Decimal('15

有人问过这个问题,但没有这样回答

在my
view.py
中,我从MySQL中提取了数据,例如数组:

(Decimal('13'), Decimal('6'), Decimal('13'))
(Decimal('207'), Decimal('18'), Decimal('129'))
(Decimal('301'), Decimal('38'), Decimal('193'))
(Decimal('204'), Decimal('32'), Decimal('150'))
(Decimal('159'), Decimal('25'), Decimal('88'))

args = {'array':array}
return render_to_response('page2.html', args)
试着把它放到谷歌图表里

function drawChart() {
    var djangoData = JSON.parse('{{ args }}');
    var data = google.visualization.arrayToDataTable(djangoData);
还尝试了
var-djangoData={{array}}
两个人都不走运

编辑1 暗示

return render_to_response('page2.html', {'array': json.dumps(array)})
看起来它可以工作,只是db产生了不兼容的类型。有没有一种方法可以在不将每个项目转换为
int
类型的情况下执行此操作。或者是否有一种蟒蛇式的方法来转化它

编辑-解决方案 使用所选答案并将
|safe
添加到数组中,因此
{{array | safe}}

您应该在view.py中尝试此操作(不要忘记添加
导入json
):

然后在模板中使用原始值数组,不带引号:

var djangoData = {{ array|safe }};
var data = google.visualization.arrayToDataTable(djangoData);
编辑:使用自定义JSONECODER处理
十进制
类型,从:

然后在视图中:

array = [['X', 'Y', 'Z'], [Decimal('1'), Decimal('2'), Decimal('3')]]
return render_to_response('page2.html', {
    'array': json.dumps(array, cls=DecimalEncoder),
})

Get Decimal('13')不可JSON序列化,这似乎是由于DB输出造成的问题。有没有一种方法可以在不将输出重新转换为不同类型的情况下解决这个问题?对这方面一点都不熟悉。多谢了,这似乎是一条正确的途径,您需要将数组(例如,
Decimal
转换为
int
),或者使用自定义JSON序列化程序动态处理转换(其实没有那么复杂)。请用你的阵法更新你的问题。现在有一些巫术正在进行。所以
var data=google.visualization.arrayToDataTable([['X','Y','Z',[1,2,3],[4,5,6]])
工作正常,但当我使用
google.visualization.arrayToDataTable({{array}})时,我什么也得不到。这是在
html
中打印的一个片段。数据似乎都是正确的,我传递列名。。。但是什么也没解决!需要将
{{array}}
更改为
{{array | safe}}
我想知道是否可以使用arrayToDataTable创建正/负列条形图?我已经成功地从视图中传递数据来绘制图表,但似乎无法绘制正常的柱状图,但难以生成正/负柱状图。有人拿着这个聊天。
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        return super(DecimalEncoder, self).default(o)
array = [['X', 'Y', 'Z'], [Decimal('1'), Decimal('2'), Decimal('3')]]
return render_to_response('page2.html', {
    'array': json.dumps(array, cls=DecimalEncoder),
})