This site runs best with JavaScript enabled.

Django & Djson… er, JSON

Photo by Luca Bravo on Unsplash

Converting a DB object to JSON format

I must admin this is my first attempt at even using JSON. I wanted to produce some data that I could consume with jQuery and I figured JSON was the best format for the job.

I found Django has a method for serializing Model query sets easily and it seemed to work just fine.

The problem I was having was that I needed information from two different models. I have Envelopes that Belong to EnvelopeCategories. I wanted to return each category with all the envelopes that belonged in that category.

I kept running into errors when I would try to serialize with Django's serializer function. Basically, if I created a dictionary with what I needed, it was serialized. If I used a query set it wouldn't add the parent fields, or any additional fields I wanted to add. But finally, after browsing around the net and piecing things together I cam up with a solution:

1from django.utils import simplejson
2from django.http import HttpResponse
3from mysite.myapp.models import EnvelopeCategory, Envelope
5def json_envelopes(request):
6 categories = EnvelopeCategory.objects.filter(user=request.user)
7 # Create dict with information to create JSON feed
8 catenvs = []
9 for cat in categories:
10 cat.envelopes = Envelope.objects.filter(category=cat)
11 envs = []
12 for env in cat.envelopes:
13 envs.append({'id':, 'name': env.title, 'order': env.order})
14 catenvs.append({'id':, 'name': cat.title, 'envelopes': envs, 'order': cat.order})
15 # Use simplejson to serialize dict
16 data = simplejson.dumps(catenvs, indent=4)
17 return HttpResponse(data, mimetype='application/javascript')

Now, on to figuring out how to consume it for me needs. 😁

Discuss on TwitterEdit post on GitHub

Share article
Dustin Davis

Dustin Davis is a software engineer, people manager, hacker, and entreprenuer. He loves to develop systems and automation. He lives with his wife and five kids in Utah.

Join the Newsletter

Dustin Davis