Serializing Django model instances

One might expect the following code to serialize a Django model instance:

import simplejson
simplejson.dumps(instance)

Unforunately, this raises a TypeError, as the instance is not JSON serializable. I don't understand why model instances are not serializable, but I do have a solution: define a serialization method on the instance's model.

def toJSON(self):
    import simplejson
    return simplejson.dumps(dict([(attr, getattr(self, attr)) for attr in [f.name for f in self._meta.fields]]))

Here's the verbose equivalent for those averse to one-liners:

def toJSON(self):
    fields = []
    for field in self._meta.fields:
        fields.append(field.name)

    d = {}
    for attr in fields:
        d[attr] = getattr(self, attr)

    import simplejson
    return simplejson.dumps(d)

_meta.fields is an ordered list of model fields which can be accessed from instances and from the model itself. _meta.fields is one of the few features not covered in Django's excellent documentation.

Respond