I am using Django with the Google Charts API. I need to construct a JavaScript array to render a bar chart showing the # of objects created in a given day.
The expected array printed to the template should look like:
...
function drawStuff() {
var data = new google.visualization.arrayToDataTable([
['Date', '# of records'],
['2015-03-07', 3], // Expected format: ['Date', # of objects]
['2015-03-08', 8],
]);
...
views.py:
class LogsView(TemplateView):
template_name = 'logs.html'
def ValuesQuerySetToDict(self, vqs):
return [ [item['date_created'], item['created_count'] ] for item in vqs]
def render_chart_data(self, **kwargs):
queryset = LogEntry.objects.filter(user=self.request.user).extra(
{'date_created': 'date(created)'}
).values('date_created').annotate(created_count=Count('id'))
modified_dict = self.ValuesQuerySetToDict(queryset)
return json.dumps(modified_dict)
def get_context_data(self, **kwargs):
context = super(
LogsView, self
).get_context_data(**kwargs)
context['chart_data'] = self.render_chart_data()
The following is rendered to my django template (I bypassed sending it to JavaScript for now to see what was returned...
When I believe I need to return a JavaScript array like the following:
["2015-02-18", 3],
["2015-02-19", 12],
["2015-02-21", 1],
And feed that to the drawStuff function which will render the barchart.
Alternate Method
I followed the this thread on StackOverflow and modified the render_chart_data to use django serializer like this but I am getting an error: " 'dict' object has no attribute '_meta'