django rest framework自定义返回格式

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

 

分享图片

 

 

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

 

分享图片

 

PS:

Python 3.7.4

djangorestframework  3.10.1

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...