Skip to content

Instantly share code, notes, and snippets.

@soerface
Last active January 18, 2019 10:11
Show Gist options
  • Save soerface/b9a9681395e36e531702224844a75163 to your computer and use it in GitHub Desktop.
Save soerface/b9a9681395e36e531702224844a75163 to your computer and use it in GitHub Desktop.
ActionSerializerMixin for the Django Rest Framework. Allows usage of multiple serializers for a single ViewSet
from typing import Union, Dict
from rest_framework.viewsets import GenericViewSet
from rest_framework.serializers import BaseSerializer
class ActionSerializersMixin(object):
"""
Allows the usage of different serializer classes depending on the action.
When your `ViewSet` class is using this mixin, it should provide a `serializer_classes` attribute instead
of a `serializer_class` attribute. This attribute must be dict, which provides for every action name the
desired serializer class (type `Dict[str, BaseSerializer]`)
Thanks to https://stackoverflow.com/a/30670569/458274
"""
serializer_classes: Dict[str, BaseSerializer] = None
# Best way to do type hinting with mixins?
# https://stackoverflow.com/a/52313062/458274
def get_serializer_class(self: Union[GenericViewSet, 'ActionSerializersMixin']) -> BaseSerializer:
assert self.serializer_classes is not None, (
f"'{self.__class__.__name__}' should include a `serializer_classes` attribute, "
f"providing a SerializerClass for each action"
)
assert self.action in self.serializer_classes, (
f"'{self.__class__.__name__}' should provide a serializer class for "
f"the action '{self.action}'"
)
return self.serializer_classes[self.action]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment