Django Rest Framework自定义返回的json格式

默认response

# view.py
from rest_framework.generics import ListAPIView
from .serializer import SnippetSerializer
from .models import Snippet

class SnippetList(ListAPIView):
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer

访问http://127.0.0.1:8000/snippets/

[
    {
    
    
        "code": "foo = \"bar\"\n",
        "id": 1,
        "language": "python",
        "linenos": false,
        "style": "friendly",
        "title": ""
    },
    {
    
    
        "code": "print(\"hello, world\")\n",
        "id": 2,
        "language": "python",
        "linenos": false,
        "style": "friendly",
        "title": ""
    }
]

自定义response

实际开发中我们需要返回更多的字段比如:

{
    
    
    "code": 0,
    "data": [], # 存放数据
    "msg": "",
    "total": ""
}

这时候就需要重写list方法:

class SnippetList(ListAPIView):
    def list(self, request, *args, **kwargs):
        queryset = Snippet.objects.all()
        response = {
    
    
            'code': 0,
            'data': [],
            'msg': 'success',
            'total': ''
        }
        serializer = SnippetSerializer(queryset, many=True)
        response['data'] = serializer.data
        response['total'] = len(serializer.data)
        return Response(response)

访问http://127.0.0.1:8000/snippets/

{
    
    
    "code": 0,
    "data": [
        {
    
    
            "code": "foo = \"bar\"\n",
            "id": 1,
            "language": "python",
            "linenos": false,
            "style": "friendly",
            "title": ""
        },
        {
    
    
            "code": "print(\"hello, world\")\n",
            "id": 2,
            "language": "python",
            "linenos": false,
            "style": "friendly",
            "title": ""
        }
    ],
    "msg": "success",
    "total": 2
}

猜你喜欢

转载自blog.csdn.net/weixin_44129085/article/details/105499198
今日推荐