Home > database >  conversion of python dictionary to json types in django rest framework
conversion of python dictionary to json types in django rest framework

Time:09-29

This is a question of comprehension rather than code issue. I am using DRF for a year. When I learnt about serializers, it says there are two steps.

For get request what serializer class do is:

  1. Converting complex datatypes like queryset into python datatype like the dictionary.
  2. Converting dictionary into json format which is sent to the api as response.

I use print commands to see everything what is happening or using the shell. I can see the first step happening ie I can see the complex queryset and after serialization can see the dictionary of the queryset. But nowhere in the code I can see the second step happening. Although the json format isnt very different from the python dictionary. The only difference I see is the double quotes instead of single quote in json. But still, the conversion needs to happen. Is it happening automatically or am I missing something here??

My snippet:

enter image description here

My prints of the queryset and serialized data:

enter image description here

Here, the email printed is the complex data. After serialization it is converted to python dictionary. However, the JSON data coming into postman is like this.

enter image description here

CodePudding user response:

Serializer.data gives you an instance of rest_framework.utils.serializer_helpers.ReturnDict which is just a light-weight wrapper around OrderedDict. OrderedDict is a further extension of Python's dict specialized for maintaining the insertion order of keys. As JSON is a text-based format for transferring data, the OrderedDict instance corresponding to the serializer is first stringified and then sent. As JSON is a standardized format, the browser is able to parse the string representation and pretty print it.

CodePudding user response:

This is being handled by Response class. Response class takes unrendered, serialized data of the response and status code as argument. If you look at the implementation it chooses the render classes based on the accepted_media_type. By default django support following renders by default.

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ]
}

In your case django uses JSONRenderer class which has a render method which does the actual serialization into JSON

  • Related