gpt4 book ai didi

python - django rest改变json响应设计

转载 作者:行者123 更新时间:2023-12-01 15:25:01 25 4
gpt4 key购买 nike

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

[
{
"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() 方法都会返回不同的值。

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

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"
}
]
}

关于python - django rest改变json响应设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38956403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com