我在这个主题上看到了一些类似的问题,但其他海报代码的结构与我为构建REST api(http://www.django-rest-framework.org/tutorial/quickstart/)所遵循的教程不同。在本教程之后,我在查询API时获得了一个未命名的JSON响应。我有serializers.py
和views.py
作为处理JSON的两个文件:
serializers.py:
from rest_framework import serializers
from main.models import Request
class RequestSerializer(serializers.ModelSerializer):
class Meta:
model = Request
fields = ('user', 'request', 'time')
views.py
class RequestViewSet(viewsets.ModelViewSet):
queryset = Request.objects.all().order_by('-time')
serializer_class = RequestSerializer
paginate_by = None
其他解决方案一直在添加return Response({"data": serializer.data})
,但我不确定在我的代码中可以添加它的位置。
答案 0 :(得分:1)
class RequestSerializer(serializers.ModelSerializer):
results_field = "your selected name"
或者您可以覆盖list
方法
def list(self, request, *args, **kwargs):
self.object_list = self.filter_queryset(self.get_queryset())
serializer = self.get_serializer(self.object_list, many=True)
return Response({'results': serializer.data})