如何从Django休息框架的序列化器获取特定字段

时间:2017-11-05 09:05:22

标签: python django django-rest-framework

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

1 个答案:

答案 0 :(得分:3)

覆盖序列化程序中的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']})

*编辑*

将其转换为mixin,使其更具可重用性:

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