Last active
May 7, 2019 18:27
-
-
Save rsudip90/69fcd8aa9ea6742b258f02df6a32b081 to your computer and use it in GitHub Desktop.
get serializer classes dynamically based on viewset actions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class GetSerializerClassMixin(object): | |
def get_serializer_class(self): | |
""" | |
under class which inhertis this mixins should have variable | |
`serializer_action_classes`. | |
Look for serializer class in self.serializer_action_classes, which | |
should be a dict mapping action name (key) to serializer class (value), | |
i.e.: | |
class SampleViewSet(viewsets.ViewSet): | |
serializer_class = DocumentSerializer | |
serializer_action_classes = { | |
'upload': UploadDocumentSerializer, | |
'download': DownloadDocumentSerializer, | |
} | |
@action | |
def upload: | |
... | |
If there's no entry for that action then just fallback to the regular | |
get_serializer_class lookup: self.serializer_class, DefaultSerializer. | |
""" | |
try: | |
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