django 在DRF中,如何在JSON响应中获取字典格式而不是字典列表

0qx6xfy6  于 2022-12-20  发布在  Go
关注(0)|答案(2)|浏览(147)

如何在JSON响应中得到字典格式而不是字典列表。现在我得到的响应像字典列表,我想得到的响应没有列表。

例如我得到的回应

[
    {
        "id": 40,
        "full_name": "Don Ser 1",
        "email": "Donny@sfds.com",
        "phone": 12345,
        "address_line_1": "sdsdsdsd",
        "address_line_2": "dsdsdsd",
   
    },
    {
        "id": 41,
        "full_name": "Don Ser 2",
        "email": "Donny@sfds.com",
        "phone": 121356456,
        "address_line_1": "sdsdsdsd",
        "address_line_2": "dsdsdsd",
    
    }
]

我喜欢得到的响应是没有列表。

[
    {
        "id": 40,
        "full_name": "Don Ser 1",
        "email": "Donny@sfds.com",
        "phone": 12345,
        "address_line_1": "sdsdsdsd",
        "address_line_2": "dsdsdsd",
     
    },
    {
        "id": 41,
        "full_name": "Don Ser 2",
        "email": "Donny@sfds.com",
        "phone": 121356456,
        "address_line_1": "sdsdsdsd",
        "address_line_2": "dsdsdsd",
  
    }
}

我如何实现这一点?另外,我想知道为什么它在列表中返回而不是字典?

wlzqhblo

wlzqhblo1#

如果你想返回一个dict,你必须定义一个结构,例如。

{'results': [
 {
        "id": 40,
        "full_name": "Don Ser 1",
        "email": "Donny@sfds.com",
        "phone": 12345,
        "address_line_1": "sdsdsdsd",
        "address_line_2": "dsdsdsd",
     
    },
    {
        "id": 41,
        "full_name": "Don Ser 2",
        "email": "Donny@sfds.com",
        "phone": 121356456,
        "address_line_1": "sdsdsdsd",
        "address_line_2": "dsdsdsd",
  
    }
]}

但是仅仅返回一个没有键的法令是不可能的。

deikduxw

deikduxw2#

如果要在DRF中返回响应,最简单的方法是:

return Response(serializer.data[0], status=status.HTTP_200_OK)

如果你想把整个字典包含在另一个字典中,你必须给予它一个键,这样它就像这样:

return Response({"results":serializer.data[0]}, status=status.HTTP_200_OK)

否则,如果您在简单项目上使用它,您可以按照您想要的方式指定它,即:

serializer = Serializer(data=request.data)
if serializer.is_valid():
    device = serializer.save()
    return Response({"pk": device.id}, status=status.HTTP_201_CREATED)

相关问题