zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    thrift python安装
    第二周习题F
    Equivalent Strings
    生成可重集的排列(方法)
    分数拆分(刘汝佳紫书P183)
    Prime ring problem
    Maximun product
    Division
    每周一赛(E题,广搜求方案)
    ICE CAVE(BFS搜索(模拟))
  • 原文地址:https://www.cnblogs.com/metasequoia/p/11625351.html
Copyright © 2011-2022 走看看