Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 768
jawilmont Avatar asked Feb 22 '12 21:02

jawilmont


People also ask

Is it necessary to use Serializers in Django?

It is not necessary to use a serializer. You can do what you would like to achieve in a view. However, serializers help you a lot. If you don't want to use serializer, you can inherit APIView at a function-based-view.

What is serializing and Deserializing in Django?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is serializing in Django?

Django's serialization framework provides a mechanism for “translating” Django models into other formats. Usually these other formats will be text-based and used for sending Django data over a wire, but it's possible for a serializer to handle any format (text-based or not).

How do I serialize Queryset?

To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.


2 Answers

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)
like image 147
Daniel Roseman Avatar answered Oct 05 '22 11:10

Daniel Roseman


building on @ducin's answer:

1) extend Django's serializer:

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

class Serializer(DjangoSerializer):  # name must be Serializer
    def get_dump_object(self, obj):
        self._current['id'] = smart_text(obj._get_pk_val(), strings_only=True)
        self._current['model'] = smart_text(obj._meta)
        return self._current

2) update the module that Django will use for type 'json':

from django.core.serializers import BUILTIN_SERIALIZERS

BUILTIN_SERIALIZERS['json'] = 'may_app.my_module'

assuming you put the Serializer above in may_app.my_module. you can put this code also in may_app.my_module, next to the Serializer.

3) from where you need to use the serializer:

from django.core import serializers
from my_app import my_module # to do the update

and then as normal:

pickle = serializers.serialize('json', MyModel.objects.all())
like image 25
mehmet Avatar answered Oct 05 '22 09:10

mehmet