drf—— 封装Response对象

1.工具类中写utils.py

# 使用自己封装的response
from rest_framework.response import Response
class APIResponse(Response):
    def __init__(self, code=100, msg='成功', data=None, status=None, headers=None, content_type=None, **kwargs):
        dic = {'code': code, 'msg': msg}
        if data:
            dic['data'] = data

        dic.update(kwargs) # 这里使用update更新
        super().__init__(data=dic, status=status,
                         template_name=None, headers=headers,
                         exception=False, content_type=content_type)

 2.views.py 使用

from app01.utils import APIResponse
class StudentApiView(APIView):
    #这样写麻烦
    # def get(self,request):
    #     res={'code':100,'msg':'成功','data':None}
    #     student_list=Student.objects.all()
    #     ser=StudentSerializer(student_list,many=True)
    #
    #     res['data']=ser.data
    #     return Response(res)
    #简单写法
    def get(self, request):
        student_list = Student.objects.all()
        ser = StudentSerializer(student_list, many=True)
        return APIResponse(code=100,msg='查询成功',data=ser.data,count=200,next='http://wwwa.asdfas')#这里返回的可以自己再加
原文地址:https://www.cnblogs.com/guojieying/p/13964204.html