一、默认response
# view
from rest_framework.generics import ListAPIView
from .serializer import IdcSerializer
from .models import Idc
class IdcList(ListAPIView):
queryset = Idc.objects.all()
serializer_class = IdcAllSerializer
http://127.0.0.1:8000/api/asset/idcall/?format=json
![](https://img2018.cnblogs.com/blog/630821/201910/630821-20191005181115906-1224892151.png)
二、自定义response
实际开发中我们需要返回更多的字段比如
{
"code": 0,
"data": [], # 存放数据
"msg": "",
"total": ""
}
这时候就需要重写list方法
# view
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
class IdcList(ListAPIView):
def list(self, request):
queryset = Idc.objects.all()
response = {
'code': 0,
'data': [],
'msg': 'success',
'total': ''
}
serializer = IdcSerializer(queryset, many=True)
response['data'] = serializer.data
response['total'] = len(serializer.data)
return Response(response)
![](https://img2018.cnblogs.com/blog/630821/201910/630821-20191005181403290-540774024.png)
PS:
Python 3.7.4
djangorestframework 3.10.1
转载于:https://www.cnblogs.com/metasequoia/p/11625351.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)