def get_serializer_context(self):
return {‘request’: self.request}
What does context do here an why do we need to mention it in our class?
def get_serializer_context(self):
return {‘request’: self.request}
What does context do here an why do we need to mention it in our class?
You use get_serializer_context()
when your serializer requires additional data from your api view. The things returned from get_serializer_context()
will be accessible in your serializer through self.context
. In other words, this is just a way of transferring data.
You will see a clear use case later in the course when you are working with nested routers.
When I did the course, I doubted myself why this code was necessary because django rest framework includes request in the context by default. I remember removing those lines and the functionality remained the same.
You can see what’s available in the context here
Also, one use case from the doc