How to get specific field from serializer of Djang

2019-07-31 04:05发布

问题:

Inside Views.py, I have these code:

class ServerViewSet(viewsets.ViewSet):

def list(self, request):
    servers = Server.objects.all()
    serializer = ServerSerializer(servers, many=True) 
    return Response(serializer.data) # In here, I want to get the server name only

def retrieve(self, request, pk=None):
    servers = get_object_or_404(Server, pk=pk)
    serializer = ServerSerializer(servers)
    return Response(serializer.data) # In here, I want to get the server name and ip address

Inside serializers.py, I have these code:

class ServerSerializer(serializers.HyperlinkedModelSerializer):
   class Meta:
        model = Server
        # fields = '__all__'
        fields = ('id', 'name', 'desc', 'ip_address')

Is there an official method to filter out the specific field from serializers.data

Sample with parent class

class CommonSerializer(serializers.ModelSerializer):
def get_field_names(self, *args, **kwargs):
    field_names = self.context.get('fields', None)
    if field_names:
        return field_names
    return super(self).get_field_names(*args, **kwargs)

class ServerSerializer(CommonSerializer):
      class Meta:
        ..............

class WebsiteSerializer(CommonSerializer):
   class Meta:
        ..............

回答1:

Override get_field_names in you serializer:

class ServerSerializer(serializers.HyperlinkedModelSerializer):
    def get_field_names(self, *args, **kwargs):
        field_names = self.context.get('fields', None)
        if field_names:
            return field_names

        return super(ServerSerializer, self).get_field_names(*args, **kwargs)

then use it like:

serializer = ServerSerializer(servers, context={'fields': ['name']})

serializer = ServerSerializer(servers, context={'fields': ['name', 'ip_address']})

* EDIT *

Turn it into mixin, to make it more reusable:

class FieldMixin(object):
    def get_field_names(self, *args, **kwargs):
        field_names = self.context.get('fields', None)
        if field_names:
            return field_names

        return super(FieldMixin, self).get_field_names(*args, **kwargs)

and use it:

class ServerSerializer(FieldMixin, serializers.HyperlinkedModelSerializer):