Search code examples
pythonjsondjangoserializationjsonserializer

Customize JSON serializer in Django


I am serializing a Django queryset which gives me an output like

[{"pk": 3, "model": "appname.somemodel", "fields": {"name": "value", "name": "value" }}]

I am only interested in the fields. So I am trying to overriding the serializer.

I have tried

from django.core.serializers.json import Serializer

class JSONSerializer(Serializer):
    def end_serialization(self):
        for i, obj in enumerate(self.objects):
            self.objects[i] = obj.get('fields', {})
        return super(JSONSerializer, self).end_serialization()

but I get an attribute error:

'JSONSerializer' object has no attribute 'objects'

I have checked https://github.com/django/django/blob/master/django/core/serializers/python.py and Serializer does have a list called objects so what is causing this problem?

Does Django have a way to omit pk and model from my serialized output?


Solution

  • In json.Serializer method end_serialization completely overridden, so for understaing how it works you need see this https://github.com/django/django/blob/master/django/core/serializers/json.py.

    Attributes pk and model added inside method get_dump_object, so you need override it.

    For example:

    from django.core.serializers.json import Serializer
    
    class JSONSerializer(Serializer):
        def get_dump_object(self, obj):
            return self._current or {}
    

    With id:

    class JSONSerializer(Serializer):
        def get_dump_object(self, obj):
            dump_object = self._current or {}
            dump_object.update({'pk': smart_text(obj._get_pk_val(), strings_only=True)})
            return dump_object