[Django]-How can i use two serializers in an APIView?

3๐Ÿ‘

โœ…

use get_serializer_class function like this

class HelloApiView(APIView):
    """Test API View"""
    serializer_class = serializers.HelloSerializer

    def get_serializer_class(self):
        if self.request.method == 'POST':
           return YOUR_SERIALIZER_1
        elif self.request.method == 'GET':
           return YOUR_SERIALIZER_2
        else:
            return YOUR_DEFAULT_SERIALIZER

    def get()

    def post(self, request):
        """Create a hello message with our name"""
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            name = serializer.validated_data.get('name')
            message = f'Hello {name}!'
            return Response({'message': message})
        else:
            return Response(
                serializer.errors,
                status=status.HTTP_400_BAD_REQUEST
            )
๐Ÿ‘คMuhammad Hassan

1๐Ÿ‘

This is quite simple to do, just overwrite the get_serializer_class method to return the serializer class based on the request method.

class HelloApiView(APIView):

    def get_serializer_class(self):
        if self.request.method.lower() == "get":
            return MyApiControllerGetSerializer 
        else:
            return MyApiControllerSerializer   

Leave a comment