在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:
..............
答案 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):