Reputation: 175
I have an actuals array of array coming from django queryset as a json. I am having trouble feeding it to the google charts.js Below is the code. views.py
def historicals(request):
actuals= serializers.serialize("json",Del.objects.all()[1:10])
json_object = json.loads(actuals)
actuals=[]
i=1
for element in json_object:
dt=element['fields']['Date']
dt=datetime.datetime.strptime(dt,'%Y-%m-%dT%H:%M:%S%z')
dt=dt.date()
dt=datetime.datetime.strftime(dt,'%Y-%m-%d')
Vol=str(element['fields']['Volume'])
print (dt)
cn=str(element['fields']['Customer'])
cn = str(cn)
actuals.append([pxn,Vol,dt])
print (actuals)
context['actuals']=actuals
return render(request,'customer.html',context)
var actuals = "{{ actuals | safe }}";
will shows the following in page source.
[['001', '5155', '2020-01-14'], ['001', '57.0', '2020-02-13'], ['001', '510', '2020-02-25'], ['001', '5760', '2020-03-23'], ['001', '46.625', '2020-03-30'], ['001', '910', '2020-04-01'], ['001', '435300.0', '2020-03-20']]
console.log(actuals); //Would show the above array of arrays
for (i = 0; i < actuals.length; i++) {
for (j = 0; j < actuals[i].length; j++) {
var dt = i;
actual = actuals[i][j]; //tried parseFloat too didnt work
//data.addRow([i,actual[i][1]);
console.log(actuals[i][j]); //--> this shows individual characters in the array [ , 0 0 0 0 1
}
}
I am trying to iteratively add a row using the data.addRow
line. My problem is actuals[i][j]
is showing an individual character (this shows individual characters in the array [ , 0 0 0 0 1....) in console.log instead of whole string or numbers or dates.
I was expecting the console.log(actuals[i][j])
to show
['001', '5155', '2020-01-14']
in the browser console. Can you help?
Upvotes: 0
Views: 222
Reputation: 175
In the context variable, I removed the quotes and the loop and charts worked very easily after that.
var actuals = {{ actuals | safe }};
Upvotes: 0
Reputation: 4988
actuals[i][j]
should show only one value.
If what you need is to pass each instance of the array as an argument to data.addRow you can use forEach, for example
actuals.forEach((entry, index) => data.addRow(index, entry));
If you need to transform the array data before using it in data.addRow()
you can do the following
actuals.forEach((entry, index) => {
const item = [+entry[0], +entry[1], new Date(entry[2])];
data.addRow(index, item);
});
The unary + operator will convert the string to number
Upvotes: 1