如何从Django的REST框架的串行获得特定领域(How to get specific fiel

2019-09-26 03:29发布

里面Views.py,我有这些代码:

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

里面serializers.py,我有这些代码:

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

有没有从serializers.data筛选出特定领域的官方方法

样品与父类

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:
        ..............

Answer 1:

覆盖get_field_names在你串行:

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)

然后使用它像:

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

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

*编辑*

把它变成混入,使之更具可重用性:

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)

并使用它:

class ServerSerializer(FieldMixin, serializers.HyperlinkedModelSerializer):


文章来源: How to get specific field from serializer of Django rest framework