一、默认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

 

django rest framework自定义返回格式

 

 

二、自定义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)

 

django rest framework自定义返回格式

 

PS:

Python 3.7.4

djangorestframework  3.10.1

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-02-21
  • 2022-12-23
  • 2021-04-14
  • 2022-12-23
  • 2021-08-22
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-11
  • 2021-09-05
  • 2022-12-23
  • 2021-08-26
  • 2022-12-23
  • 2021-10-21
相关资源
相似解决方案