python - 使用 Django 将数据传递给 Google Charts

标签 python mysql django

这个问题已经被问到但没有这样回答one .

在我的 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)

尝试将其放入 Google Chart

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)})

看起来它可以工作,除了数据库产生不兼容的类型。有没有一种方法可以在不将每个项目都转换为 int 类型的情况下执行此操作。或者是否有 pythonic 方式来转换它?

编辑 - 解决方案

使用选择的答案并将|safe添加到数组中,所以{{array|safe}}

最佳答案

你应该在 view.py 中尝试这个(不要忘记添加 import json):

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

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

var djangoData = {{ array|safe }};
var data = google.visualization.arrayToDataTable(djangoData);

编辑:使用自定义 JSONEncoder 处理 Decimal 类型,从 this question 中窃取:

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return float(o)
        return super(DecimalEncoder, self).default(o)

然后在 View 中:

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

关于python - 使用 Django 将数据传递给 Google Charts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20830679/

相关文章:

python - 查找总和为零的向量集

python - 在 Django 中, super 用户是否可以拥有与非 super 用户不同的必填字段?

php - MySQL 未知列错误,但结果似乎正常,并且查询在 phpMyAdmin 中工作

php - 在存储过程之外提交事务

php - wordpress查询所有以数字开头的帖子

django - 我可以限制 Wagtail 管理图像选择器中的可见集合吗?

django - 如何获取 django 查询的最后 n 个对象?

python - 检查字符串是否包含任意数量的数字后跟特定字母 [Python]

python - 使用任意数量的键/值对构造字典

python - 加密的 Django 模型字段