Send JSON Graph Data from Django
1 min read

Send JSON Graph Data from Django

Send JSON Graph Data from Django

I'm trying to write a Django application to deal with my finances. I've got a nice page listing various transactions, but I thought it'd be nice to have a graph too, to see where I actually am on the spot. To do this, I'll need two components:

  1. A JSON sender from Django
  2. A receiver and renderer on the web page

The sender from django can be done in may ways... I can do it via the REST framework, or "manual". My initial iplementation is "manual" :)

My model has 2 essential fields: A DateField "date" and a DecimalField "amount".. First, I'll need to extract the data:

def transaction_chart_json(request):
      data= Transaction.objects.annotate(
          x=Cast(TruncDay('date', DateField()), CharField()),
          y=Cast('amount', FloatField()),
      return JsonResponse({'data': list(data)})

The logic is quite simple: I'll convert the DateFieldto a CharField containing only the date part (e.g. DD/MM/YYY) and the DecimalFieldto a FloatField.

I then send each transaction to the web page as a tuple of (date, amount), to keep it simple. The date is a string and the amount will be a floating point number. The structure is something like:

  "data": [{ "x": "2018-02-01", "y": 10568.2 }, { "x": "2018-02-12", "y": 7.5 }]

Note: This approach is not really indicated, because it has no security in place and using Django REST Framework is much more elegant. However, this server my purpose for the time being.