Created
October 1, 2015 18:00
-
-
Save cmdelatorre/9a73db3f88e7934f01d4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# Based on http://stackoverflow.com/a/22922156/1161156 | |
class MultiSerializerViewSetMixin(object): | |
def get_serializer_class(self): | |
""" | |
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 MyViewSet(MultiSerializerViewSetMixin, ViewSet): | |
serializer_class = MyDefaultSerializer | |
serializer_action_classes = { | |
'list': MyListSerializer, | |
'my_action': MyActionSerializer, | |
} | |
@action | |
def my_action: | |
... | |
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(MultiSerializerViewSetMixin, self).get_serializer_class() | |
class SomeModelViewSet(MultiSerializerViewSetMixin, viewsets.ModelViewSet): | |
queryset = SomeModel.objects.all() | |
serializer_action_classes = { | |
'list': SomeModelListSerializer, | |
'create': SomeModelUpdateSerializer, | |
#'retrieve': , | |
'update': SomeModelUpdateSerializer, | |
'partial_update': SomeModelUpdateSerializer, | |
#'destroy': , | |
} | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment