Handle multiple serializers for the same view in Django Rest Framework.
This package uses uv for project management. To get started, ensure that uv is installed on your machine and updated to the 0.5.13
version. Detailed installation instructions for uv can be found here.
uv add drf-multi-serializers
Simply import the MultiSerializerMixin
and use it in your API views:
from rest_framework.generics import ListCreateAPIView
from rest_framework.viewsets import ModelViewSet
from drf_multi_serializers import MultiSerializerMixin
...
class MyListCreateAPIView(MultiSerializerMixin, ListCreateAPIView):
...
serializer_classes = {
"create": MyCreateSerializer,
"list": MyListSerializer,
}
...
class MyViewSet(MultiSerializerMixin, ModelViewSet):
...
serializer_classes = {
"create": MyCreateSerializer,
"list": MyListSerializer,
"metadata": MyMetadataSerializer, # create ViewSets require either serializer_class or metadata serializer for OPTION requests
"partial_update": MyUpdateSerializer,
"retrieve": MyRetrieveSerializer,
"update": MyUpdateSerializer,
}
...
drf-multi-serializers
also supports Django Rest Framework's versioning system!
from rest_framework.generics import ListCreateAPIView
from rest_framework.viewsets import ModelViewSet
from drf_multi_serializers import MultiSerializerMixin
...
class MyAPIView(MultiSerializerMixin, APIView):
...
serializer_classes = {
"v1": MyV1Serializer,
"v2": MyV2Serializer,
}
...
class MyViewSet(MultiSerializerMixin, ModelViewSet):
...
serializer_classes = {
"create": {"v1": MyV1CreateSerializer, "v2": MyV2CreateSerializer},
"list": MyListSerializer,
"metadata": MyMetadataSerializer, # create ViewSets require either serializer_class or metadata serializer for OPTION requests
"partial_update": MyUpdateSerializer,
"retrieve": MyRetrieveSerializer,
"update": MyUpdateSerializer,
}
...
uv sync --frozen --group=development
uv run --frozen pre-commit install --install-hooks
uv run --frozen pre-commit install --hook-type=commit-msg
Contributions are welcome! To get started, please refer to our contribution guidelines.
If you encounter any problems while using this package, please open a new issue here.