I am struggling to use data stored in datastore to render a google chart. At the moment I have queried the data model:
results = MyDataModel.query().fetch()
It is at this stage I am unsure what to do. For example, is it best to create a list in python like:
result_list = []
for result in results:
result_list.append([result.employee, result.salary])
and then using Jinja2 templates pass it into an array table:
var data = google.visualization.arrayToDataTable([
['Employee Name', 'Salary'],
{% for result in result_list %}
{{result | safe}}
{% endfor %},
false);
Or is it best to dynamically add row data into a DataTable or is it best to query the data store directly?
Which ever way I try I am struggling to render anything at all. Any help would be appreciated.
You've got the right idea with inserting the data into your Jinja2 template. It looks like you are just not formatting your inputs to google.visualization.arrayToDataTable correctly. Note that one of your open square brackets ( [ ) is not closed.
Below is an example of how I have done this in case it helps you. You can see it live here.
There is no point in creating the result_list array. The results query is going to be processed regardless and it doesn't matter if it is being done in your handler or in the template.
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With