Skip to content

Handle multiple serializers for the same view in Django Rest Framework

License

Notifications You must be signed in to change notification settings

stefanofusai/drf-multi-serializers

Repository files navigation

drf-multi-serializers

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.

Installation

uv add drf-multi-serializers

Usage

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,
    }
    ...

Development

uv sync --frozen --group=development
uv run --frozen pre-commit install --install-hooks
uv run --frozen pre-commit install --hook-type=commit-msg

Contributing

Contributions are welcome! To get started, please refer to our contribution guidelines.

Issues

If you encounter any problems while using this package, please open a new issue here.

About

Handle multiple serializers for the same view in Django Rest Framework

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •  

Languages