Custom output with serializer in Django Rest Frame

2019-06-01 05:02发布

问题:

I'd like to display custom output, i.e success=true when a user object is created.

This is the code I have now which works fine:

class UserViewSet(viewsets.ViewSet):
    queryset = User.objects.all()

    def post(self, request, *args, **kwargs):
        # ... do some stuff
        return Response('some custom response')

My problem is that I also need to have some fields required, e.g username and password.

I'm assuming I need a serializer for that. Adding a serializer to my ViewSet and now I have another problem. I can't get it to return my custom output.

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'is_staff')

    def restore_object(self, attrs, instance=None):
        #... do some stuff
        return Response('sadf') # obviously this won't work

I'm trying to find the method to override that controls the output of the serializer but I can't find it.

回答1:

The method you are looking for is to_native.

class UserSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'is_staff')  


     def to_native(self, obj):
         return 'some custom response'

Note that to_native is renamed to to_representation in Django Rest Framework 3.0