将对象列表作为字典返回,键作为对象 id 使用 django rest framerwork [英] Return list of objects as dictionary with keys as the objects id with django rest framerwork
本文介绍了将对象列表作为字典返回,键作为对象 id 使用 django rest framerwork的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前,我有一个 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)返回 {res['id']: res}# 也可以直接通过数据获取id# return {str(data.id): res}
Currently, I have a ListAPIView that returns a list of object dictionaries:
[
{ id: 1, ...},
{ id: 2, ...},
...
]
I would like to change this to be formatted as a dictionary with the id as the key:
{
"1": { id: 1, ...},
"2": { id: 2, ...},
...
}
How do I customize the output in this way using Django Rest Framework? Currently I am doing the re-formatting client side, but I would like to do it server side.
解决方案
I think you can implement the to_representation
function in your Serializer.
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}
这篇关于将对象列表作为字典返回,键作为对象 id 使用 django rest framerwork的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文