Created
July 13, 2014 10:33
-
-
Save mlalic/32cc498215fa7c1c31df to your computer and use it in GitHub Desktop.
Mixin for the DjangoRestFramework ViewSet providing the ability to choose a different serializer based on the view action.
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 MultiSerializerViewSetMixin(object): | |
""" | |
Mixin for the DRF ViewSet providing the ability to choose a different | |
serializer based on the view action. | |
Classes mixing it in need to provide the ``serializer_classes`` | |
dictionary mapping an action to a serializer class. | |
If a particular action does not have a custom serializer attached to it, | |
the mixin delegates the call up the MRO (Method Resolution Order). | |
Example usage:: | |
from rest_framework import viewsets | |
class ModelViewSet(MultiSerializerViewSetMixin, viewsets.ModelViewSet): | |
model = SomeModel | |
#: Provide a default model serializer like usual | |
serializer_class = DefaultModelSerializer | |
#: Provide an overide for the serializer for two actions | |
serializer_classes = { | |
'list': ListModelSerializer, | |
'create': CreateModelSerializer, | |
} | |
""" | |
def get_serializer_class(self): | |
if self.action in self.serializer_classes: | |
return self.serializer_classes[self.action] | |
return super(MultiSerializerViewSetMixin, self).get_serializer_class() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment