0

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

2 Answers 2

1

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 renderers 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

Sign up to request clarification or add additional context in comments.

1 Comment

Very very good explanation Abdul. Thanks!
1

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.

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.