本文介绍了如何从Django Rest框架的序列化器获取特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Views.py内部,我有以下代码:

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

在serializers.py内部,我有以下代码:

Inside serializers.py, I have these code:

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

是否有一种官方方法可以从serializers.data中过滤出特定字段

Is there an official method to filter out the specific field from 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:
        ..............


推荐答案

覆盖 get_field_names 在您的序列化程序中:

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)

然后使用它:

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

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

*编辑*

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

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)

并使用它:

class ServerSerializer(FieldMixin, serializers.HyperlinkedModelSerializer):

这篇关于如何从Django Rest框架的序列化器获取特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 21:37