Allow to extend serializer context using kwargs of get_serializer method#6956
Allow to extend serializer context using kwargs of get_serializer method#6956Olerdrive wants to merge 1 commit into
get_serializer method#6956Conversation
get_serializer method
|
Hi @Olerdrive. I'd argue that you shouldn't leverage the context here. Instead, def get_serializer_context(self):
context = super().get_serializer_context()
context['context_key'] = 'value'
return context |
|
@rpkilby there are cases where actually this would make things much simpler and make code more consistent. In my case for example I need to pass some metadata when uploading a file (e.g. reading the headers of an MPEG), but I still want to keep all other views to return just 'request' and 'view'. The solution you mention, does not work in my case since the context comes from a specific view - |
|
@Pithikos you could inspect the viewset properties, such as def get_serializer_context(self):
context = super().get_serializer_context()
if self.action == 'list':
context['context_key'] = 'value'
return context |
|
I'd agree that it would be preferable to provide the context explicitly in the call to def get_serializer(self, *args, **kwargs):
"""
Return the serializer instance that should be used for validating and
deserializing input, and for serializing output.
"""
serializer_class = self.get_serializer_class()
kwargs.setdefault('context', self.get_serializer_context())
return serializer_class(*args, **kwargs)The above allows the user to override the context, without merging them. |
Fixes #6955
Description
As I mentioned in the #6955 it is impossible to pass any extra context to the serializer from the generic Viewset as it will be overwritten with the default value in the
get_serializermethod.My pull request fixes this allowing the default context to be extended with the provided one.