Issue
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:
- Converting complex datatypes like queryset into python datatype like the dictionary.
- 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:
My prints of the queryset and serialized data:
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.
Solution
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
Answered By - Abdul Niyas P M
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.