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