I\'m trying to write a very basic bar graph using Django and D3.js. I have an object called play with a datetime field called date. What I want to do is show number of plays
I loved what fernando-macedo put together and it got me to a certain point with my data.
However I struggled with filtering of data as opposed to passing the entire dataset via this api setup. This is very similar to other peoples problem of passing JSON data from a Queryset and Pavel Patrin's answer helped me with that.
So this will now allow people to filter their data and send it as a json for use in d3. Now I am using the same hypothetical example but it should work for
# views.py
from django.db import connections
from django.db.models import Count
# from django.http import JsonResponse #no longer needed
from django.shortcuts import render
import json
from .models import Play
def graph(request):
data = Play.objects.filter(name__startswith='Test') \ #change here for filter. can be any kind of filter really
.extra(select={'month': connections[Play.objects.db].ops.date_trunc_sql('month', 'date')}) \
.values('month') \
.annotate(count_items=Count('id'))
formattedData=json.dumps([dict(item) in list(data)]) #This is a two-fer. It converts each item in the Queryset to a dictionary and then formats it using the json from import json above
#now we can pass formattedData via the render request
return render(request, 'graph/graph.html',{'formattedData':formattedData})
Now to get that appropriately on the other side (the html side)
Anyways, I hope this saves someone some time with Django and/or D3 as this solves two issues at once.