Django & Djson… er, JSON

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:

?View Code PYTHON
from django.utils import simplejson 
from django.http import HttpResponse 
from mysite.myapp.models import EnvelopeCategory, Envelope
 
def json_envelopes(request): 
    categories = EnvelopeCategory.objects.filter(user=request.user) 
    # Create dict with information to create JSON feed 
    catenvs = [] 
    for cat in categories: 
        cat.envelopes = Envelope.objects.filter(category=cat) 
        envs = [] 
        for env in cat.envelopes: 
            envs.append({'id': env.id, 'name': env.title, 'order': env.order}) 
        catenvs.append({'id': cat.id, 'name': cat.title, 'envelopes': envs, 'order': cat.order}) 
    # Use simplejson to serialize dict
    data = simplejson.dumps(catenvs, indent=4) 
    return HttpResponse(data, mimetype='application/javascript')

Now, on to figuring out how to consume it for me needs… :D

Related posts:

  1. IE & JSON Caching Bug I came across a weird bug. It seems that IE...
  2. Mobile App on Subdomain with Django I’ve noticed a fairly common pattern arising with mobile and...
  3. Django: Login Form on Every Page Up to the point, when it has come to Django...
  4. Django cron on Webfaction James Bennett addresses one of the most frequently asked questions...
  5. Copy Model Object in Django I ran into a situation where I wanted to created...

Related posts brought to you by Yet Another Related Posts Plugin.

May 21, 2009  Tags: , , , ,   Posted in: Programming & Internet

7 Responses

  1. Matthew - May 21, 2009

    My full serializers might be what you are after.

    http://wadofstuff.blogspot.com/2009/02/django-full-serializers-part-i.html
    http://wadofstuff.blogspot.com/2009/02/django-full-serializers-part-ii.html

  2. Dustin - May 21, 2009

    Yes, I definitely could have used that about 3 hours ago! :D

  3. Jesper Noehr - May 21, 2009

    You might want to have a look at django-piston: http://bitbucket.org/jespern/django-piston/wiki/Home

  4. 汇率网 - May 22, 2009

    Yes, it’s very useful.
    Thanks.

  5. Mark - June 24, 2009

    Great work – I was having problems with Django serialize:
    r = [u'ABC', u'DEF']
    serializers.serialize(“json”, r)
    was giving the error:
    AttributeError: ‘unicode’ object has no attribute ‘_meta’
    SimpleJSON did the trick.

  6. windows - August 3, 2009

    Django is a bit of an animal but this script is very helpful. Also thanks Jesper for that link

  7. Martin - October 28, 2009

    Thank you, thank you, thank you! :)

Leave a Reply