Friday, July 09, 2010

Doing ajax with django models serialization: json part

Finally a technical post after a long while, here goes

On my new job, the site requires a crazy level of interactivity, probably for the wrong reason, but lets not go there now.

Along the way, we decide to use a mix of javascript, and html, with a help of json. Thats is where, django serialization comes in. What it does is, it serialize a django queryset into xml or json. If i need to use that to generate json for django queryset, because simplejson cannot do it, not directly.

To output a queryset to json is pretty easy.


from django.core import serializers
data = serializers.serialize('json', queryset)


where queryset your djangoqueryset


in a sample database, in a called addressbook





to play around with the django shell, assume that data already there


>>> from django.core import serializers
>>> from addressbook.models import Contact
>>> serializers.serialize('json', Contact.objects.all())
[{"pk": 1, "model": "addressbook.contacts", "fields": {"phone": "012345678", "post_code": "68100", "name": "sweemeng", "address": "somewhere in selayang"}}]


To make it useful for my purpose to use in a javascript, i need to put this into a views, point your urls.py to the views, and run the server, and point your browser to it, you should able to see a json output





But here is the catch, one, this is strictly only for serializing django queryset, you can still use simplejson for other type of data. two it seems that django serializer don't serialize a single model instance.


Next post, using it with a jquery

more information on django serialization