Getting Django to serialize objects without the "fields" field

jawilmont picture jawilmont · Feb 22, 2012 · Viewed 10.5k times · Source

So I am working on writing the backend web service using Django to create & consume JSON, and my colleague is working on the ExtJS4 frontend. I'm using the wadofstuff serializer so I can serialize nested objects.

My colleague is having trouble parsing the json, specifically that Django puts the fields for an object inside a "fields" field. A short example:

The way things are being serialized now:

{
  "pk":1,
  "model":"events.phone",
  "fields":{
     "person":1,
     "name":"Cell",
     "number":"444-555-6666"
  }
}

The way I would like to serialize them to make ExtJS and my fellow developer happy:

{
  "pk":1,
  "model":"events.phone",
  "person":1,
  "name":"Cell",
  "number":"444-555-6666"
}

We will need to serialze some objects that are much more complicated than this however.

Is there any way short of writing my serializations by hand to make the Django or wadofstuff serializer not use a fields field?

Answer

ducin picture ducin · Apr 22, 2013

Additionally, there's a more flexible way of modifying the general model JSON output in django. Take a look at the django.core.serializers module source code (which is quite simple - I'm a python newbie) and override the get_dump_object method:

from django.core.serializers.json import Serializer as Builtin_Serializer

class Serializer(Builtin_Serializer):
    def get_dump_object(self, obj):
        return self._current

In above example I get rid of both pk and model keys and I return the fields immediately.

The original code is:

def get_dump_object(self, obj):
    return {
        "pk": smart_text(obj._get_pk_val(), strings_only=True),
        "model": smart_text(obj._meta),
        "fields": self._current
    }

The solution to the original question could be, for example:

def get_dump_object(self, obj):
    metadata = {
        "pk": smart_text(obj._get_pk_val(), strings_only=True),
        "model": smart_text(obj._meta),
    }
    return dict(metadata.items() + self._current.items())