Search code examples
djangojsonextjs4

Getting Django to serialize objects without the "fields" field


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?


Solution

  • The best way to customize your serialization is to get Django to serialize to Python dicts first. Then you can post-process those dicts however you like, before dumping them out to JSON:

    # this gives you a list of dicts
    raw_data = serializers.serialize('python', Phone.objects.all())
    # now extract the inner `fields` dicts
    actual_data = [d['fields'] for d in raw_data]
    # and now dump to JSON
    output = json.dumps(actual_data)