我正在努力使用存储在数据存储区中的数据来呈现Google图表。目前,我已经查询了数据模型:

results = MyDataModel.query().fetch()


在这个阶段,我不确定该怎么做。例如,最好在python中创建一个列表,例如:

result_list = []
for result in results:
    result_list.append([result.employee, result.salary])


然后使用Jinja2模板将其传递到数组表中:

var data = google.visualization.arrayToDataTable([
   ['Employee Name', 'Salary'],
   {% for result in result_list %}
    {{result | safe}}
   {% endfor %},
  false);


还是最好将行数据动态添加到DataTable中,还是最好直接查询数据存储?

无论尝试哪种方式,我都在努力渲染任何东西。任何帮助,将不胜感激。

最佳答案

将数据插入Jinja2模板时,您已经有了正确的主意。看来您只是没有将输入正确格式化为google.visualization.arrayToDataTable。请注意,未打开方括号([)之一。

下面是一个如何帮助您的示例。您可以实时查看here

创建result_list数组没有意义。 results查询将被处理,无论是在您的处理程序中还是在模板中完成都无关紧要。

<script type="text/javascript">
var data = new google.visualization.DataTable();
data.addColumn("string", "Candidate");
data.addColumn("number", "Votes");
data.addColumn({type:"string", role:"tooltip"});
data.addColumn({type: "boolean", role:"certainty"});
data.addColumn("number", "Received");
data.addColumn({type:"string", role:"tooltip"});
data.addColumn("number", "Transferred");
data.addColumn({type:"string", role:"tooltip"});
data.addRows([["Vanilla", 110.000000, "Votes: 110", true, 0.000000, "Votes: 110", 0.000000, "Votes: 110"],["Chocolate", 117.000000, "Votes: 117", true, 0.000000, "Votes: 117", 0.000000, "Votes: 117"],["Strawberry", 80.000000, "Votes: 80", true, 0.000000, "Votes: 80", 0.000000, "Votes: 80"],["Chocolate Chip", 103.000000, "Votes: 103", true, 0.000000, "Votes: 103", 0.000000, "Votes: 103"],["Cookies and Cream", 118.000000, "Votes: 118", true, 0.000000, "Votes: 118", 0.000000, "Votes: 118"],["Exhausted", 0.000000, "Votes: 0", true, 0.000000, "Votes: 0", 0.000000, "Votes: 0"]]);
var formatter = new google.visualization.NumberFormat({fractionDigits:0});
formatter.format(data, 1);
formatter.format(data, 3);
formatter.format(data, 5);
var options = {
width:'100%',
height:200,
legend:{position:"none"},
chartArea:{left:100,top:0,width:'100%',height:175},
hAxis:{maxValue:276},
isStacked:true,
colors:["#fcd050", "#87cf32", "#ef3638"],
};
var chart = new google.visualization.BarChart(document.getElementById("282249-1"));
chart.draw(data, options);
</script>

关于python - 使用数据存储区数据渲染Google图表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30397727/

10-12 16:57
查看更多