While it looks like you can serialize a queryset of 1 object, you cannot use the classes from django.core to do this. Any particular reason not to use serialize the queryset?
–
Jack M.Apr 16 '09 at 17:03

1

The queryset serializer wraps the result in two more layers than it has to. So you have to do data[0].fields.name instead of data.name.
–
Jason ChristaApr 16 '09 at 17:37

That's what I thought. I ran into that same issue when I was writing a GWT interface for a django backend. Looks like David might be onto something.
–
Jack M.Apr 16 '09 at 17:48

It sounds like what you're asking about involves serializing the data structure of a Django model instance for interoperability. The other posters are correct: if you wanted the serialized form to be used with a python application that can query the database via Django's api, then you would wan to serialize a queryset with one object. If, on the other hand, what you need is a way to re-inflate the model instance somewhere else without touching the database or without using Django, then you have a little bit of work to do.

Here's what I do:

First, I use demjson for the conversion. It happened to be what I found first, but it might not be the best. My implementation depends on one of its features, but there should be similar ways with other converters.

Second, implement a json_equivalent method on all models that you might need serialized. This is a magic method for demjson, but it's probably something you're going to want to think about no matter what implementation you choose. The idea is that you return an object that is directly convertible to json (i.e. an array or dictionary). If you really want to do this automatically:

This will not be helpful to you unless you have a completely flat data structure (no ForeignKeys, only numbers and strings in the database, etc.). Otherwise, you should seriously think about the right way to implement this method.

I haven't tried the code yet but I just wanted to point out some errors in it. It is instance._meta.get_all_field_names() and getattribute is a function so should have () and not [].
–
Jason ChristaApr 16 '09 at 19:27

Good points. Chock it up to bad typing.
–
David BergerApr 16 '09 at 20:22

in addition to FK, this will not work for datetime fields (unless there is magic in demjson.JSON.encode)
–
Skylar SavelandSep 11 '10 at 19:10

Although the idea might seem good at first, one should point out that there are consequences to using this approach. You are tying one specific serialization output to your model.
–
Jonas GeiregatMay 16 '13 at 22:21