gpt4 book ai didi

python - 使用 django rest framerwork 返回对象列表作为字典,键作为对象 id

转载 作者:太空狗 更新时间:2023-10-29 20:18:31 25 4
gpt4 key购买 nike

目前,我有一个返回对象字典列表的 ListAPIView:

[
{ id: 1, ...},
{ id: 2, ...},
...
]

我想将其更改为格式化为以 id 为键的字典:

{
"1": { id: 1, ...},
"2": { id: 2, ...},
...
}

如何使用 Django Rest Framework 以这种方式自定义输出?目前我正在重新格式化客户端,但我想在服务器端进行。

最佳答案

我认为您可以在序列化程序中实现 to_representation 函数。

class MySerializer(serializers.Serializer):
id = serializers.ReadOnlyField()
field1 = serializers.ReadOnlyField()
field2 = serializers.ReadOnlyField()

def to_representation(self, data):
res = super(MySerializer, self).to_representation(data)
return {res['id']: res}
# or you can fetch the id by data directly
# return {str(data.id): res}

关于python - 使用 django rest framerwork 返回对象列表作为字典,键作为对象 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29930401/

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