如何自定义Django Rest Framework的返回数据格式?
- 内容介绍
- 文章标签
- 相关推荐
本文共计328个文字,预计阅读时间需要2分钟。
一、伪原创开头内容:
原创:在这个快速发展的时代,创新成为了推动社会进步的重要力量。
伪原创:在这个日新月异的时代,创新始终是引领社会发展的核心动力。
二、伪原创内容:
原创:众多创新型企业纷纷涌现,为我国经济发展注入了新的活力。
伪原创:众多创新型企业如雨后春笋般崛起,为我国经济注入源源不断的活力。
一、默认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
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
djangorestframework3.10.1
本文共计328个文字,预计阅读时间需要2分钟。
一、伪原创开头内容:
原创:在这个快速发展的时代,创新成为了推动社会进步的重要力量。
伪原创:在这个日新月异的时代,创新始终是引领社会发展的核心动力。
二、伪原创内容:
原创:众多创新型企业纷纷涌现,为我国经济发展注入了新的活力。
伪原创:众多创新型企业如雨后春笋般崛起,为我国经济注入源源不断的活力。
一、默认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
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
djangorestframework3.10.1

