django restframework默认的ListCreateAPIView,返回格式如下,直接返回查询field的查询结果
{
"id": 1,
"desc": "Java讨论会Java讨论会",
"name": "Java讨论会",
}
但是实际开发中需要定制返回结果,如下
{
"retcode": 200,
"msg": "查询成功",
"retlist": [
{
"id": 1,
"desc": "Java讨论会Java讨论会",
"name": "Java讨论会",
}
]
}
通过重写ListCreateAPIView,新建genericsview.py
from rest_framework import generics
from rest_framework.response import Response
# 重写查询返回格式
class ReListView(generics.ListCreateAPIView):
def list(self, request, *args, **kwargs):
# 重写response 返回信息
response = {‘retcode‘: 200, ‘msg‘: ‘查询成功‘}
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
# 将原来的结果放进response字典
response[‘retlist‘] = serializer.data
return Response(response)
原来view中继承ListCreateAPIView的替换成自己重写的ReListView
class ProjectList(ReListView):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
重启django,返回结果成功加上了自己新增的返回字段
重写render的方法需要,需要setting中增加配置,重写JSONRenderer中的render方法
优点:全局改写
缺点:restframework自带的界面用不了,暂时还没找到解决方法
? 不同请求方式,需要判断不同请求的返回内容
ListCreateAPIView,其他四个View也可以使用重载的方法重写,只需要重写5个APIView
django,restframework,GenericAPIView重写返回格式
原文:https://www.cnblogs.com/gotesting1/p/14615033.html