Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
drf serializer class dynamic --
class GetSerializerClassMixin(object):
def get_serializer_class(self):
A class which inhertis this mixins should have variable
Look for serializer class in self.serializer_action_classes, which
should be a dict mapping action name (key) to serializer class (value),
class SampleViewSet(viewsets.ViewSet):
serializer_class = DocumentSerializer
serializer_action_classes = {
'upload': UploadDocumentSerializer,
'download': DownloadDocumentSerializer,
def upload:
If there's no entry for that action then just fallback to the regular
get_serializer_class lookup: self.serializer_class, DefaultSerializer.
return self.serializer_action_classes[self.action]
except (KeyError, AttributeError):
return super().get_serializer_class()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.