Use different serializer for request and reply

2019-08-30 06:45发布

问题:

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?

回答1:

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)


回答2:

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)