django rest change json 响应设计

django rest change json response design

我正在使用 Django rest 教程,我看到所有响应 return 只有模型字段,例如:

[
  {
    "id": 1,
    "title": "",
    "code": "foo = \"bar\"\n",
    "linenos": false,
    "language": "python",
    "style": "friendly"
  }]

我的问题是如何设计响应,例如:

  users:[
   {
        "id": 1,
        "title": "",
        "code": "foo = \"bar\"\n",
        "linenos": false,
        "language": "python",
        "style": "friendly"
      }]

据我所知,您正在使用以下代码,我已对其进行修改以执行您的请求。但是,我建议除非您有充分的理由这样做,否则不要修改给出响应的方式。它会导致将来为 ModelViewSets 创建多个对象时变得复杂,并且所有 list() 方法都会 return 不同的值。

我真的不喜欢下面的内容,但它确实回答了问题。此外,您可以将序列化程序更改为嵌套序列化程序,但这本身就是另一个问题。

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer


@api_view(['GET', 'POST'])
def snippet_list(request):
    """
    List all snippets, or create a new snippet.
    """
    if request.method == 'GET':
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return Response({'users': serializer.data})

    elif request.method == 'POST':
        # Assuming we have modified the below - we have to hack around it
        serializer = SnippetSerializer(data=request.data['users'])
        if serializer.is_valid():
            serializer.save()
            return Response({'users': serializer.data}, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

以上应该会给你以下的回应:

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