[Answered ]-Multiple Serializer within the same view.list call

1👍

Option 01 – Overriding the to_representation method:

from rest_framework.serializers import ModelSerializer


class ExampleSerializer(ModelSerializer):

    class Meta:
        model = Example
        fields = "__all__"

    def to_representation(self, instance):
        if isinstance(instance, Example) and not instance.is_private:
            return super().to_representation(instance)

        result = dict(custom_field=instance.name, another_custom_field=instance.is_private)

        return result

Option 02 – Using two serializers in one view:

from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from .serializers import ExampleSerializer, AnotherExampleSerializer


class AnyView(ListAPIView):
    # Create a new attribute to store the serializers
    serializers_classes = (ExampleSerializer, AnotherExampleSerializer)

    # One way to do it
    def list(self, request, *args, **kwargs):
        if <some_specific_condition>:
            self.serializer_class = self.serializers_classes[0]
            return super().list(request, *args, **kwargs)

        self.serializer_class = self.serializers_classes[1]
        return super().list(request, *args, **kwargs)

    # Another way to do it
    def list(self, request, *args, **kwargs):
        if <some_specific_conditition>:
            serializer = self.serializers_classes[0](self.get_queryset(), many=True)

            if serializer.is_valid():
                return Response(data=serializer.data, status=HTTP_200_OK)

            return Response(data=serializer.errors, status=HTTP_400_BAD_REQUEST)

        serializer = self.serializers_classes[1](self.get_queryset(), many=True)

        if serializer.is_valid():
            return Response(data=serializer.data, status=HTTP_200_OK)

        return Response(data=serializer.errors, status=HTTP_400_BAD_REQUEST)

Maybe you will need to override the get_queryset to return the fields differently if private is True.

In my opinion, overriding the to_representation method of serializer will be enough to do it.

Leave a comment