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
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章