blueFast
blueFast

Reputation: 44371

Use different serializer for request and reply

I can use different serializers for POST / GET requests as follows:

class CommandViewSet(DynamicModelViewSet):
    queryset = Command.objects.all()
    serializer_class_post = CommandSerializerPost
    serializer_class_get = CommandSerializerGet
    permission_classes = (AllowAny,)

    def get_serializer_class(self):
        if self.request.method == 'POST':
            return self.serializer_class_post
        elif self.request.method == 'GET':
            return self.serializer_class_get

Now I would like to use a different serializer for the request and the reply of a POST request. How can this be accomplished?

Upvotes: 11

Views: 7903

Answers (2)

Ali
Ali

Reputation: 2591

You can receive data by MySerializer1 and response to request by MySerializer2

Class MyView(APIView):
    def post(selft, request):
        serializer1 = MySerializer1(request.data)
        # other codes
        serializer2 = MySerializer2(changedData)
        return response(serializer2.data)

Upvotes: 5

neverwalkaloner
neverwalkaloner

Reputation: 47354

You can override serializer's to_representation() method for this:

class CommandSerializerPost(serializers.ModelSerializer):
    # yur code here

    def to_representation(self, instance):
        serializer = CommandSerializerGet(instance)
        return serializer.data

UPD

In above code, CommandSerializerPost will always returns the output of CommandSerializerGet, irrespective of the request.method. So it should be like this if you need to change respnse only for GET request:

class CommandSerializerPost(serializers.ModelSerializer):

    def to_representation(self, instance):
        if self.context['request'].method == 'GET':
            serializer = CommandSerializerGet(instance)
            return serializer.data
        return super().to_representation(instance)

Upvotes: 12

Related Questions