目前,我有一个ListAPIView,它返回一个对象字典列表:
[
{ id: 1, ...},
{ id: 2, ...},
...
]
我想将其更改为格式化为id为键的字典:
{
"1": { id: 1, ...},
"2": { id: 2, ...},
...
}
如何使用Django Rest Framework以这种方式自定义输出?目前我正在进行重新格式化客户端,但我想在服务器端进行。
答案 0 :(得分:5)
我认为您可以在Serializer中实现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}
答案 1 :(得分:4)
您可以遍历每个项目并使用词典理解创建所需的词典。例如:
>>> l = [{ "id": 1, "x": 4}, { "id": 2, "x": 3}]
>>> {v["id"]: v for v in l}
{1: {'x': 4, 'id': 1}, 2: {'x': 3, 'id': 2}}
答案 2 :(得分:2)
编辑:Github project和PYPI(pip install drf-keyed-list
)中可用的当前版本
这是一个双向通用类(相对于上面的只读实现):
class KeyedListSerializer(ListSerializer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
meta = getattr(self.child, 'Meta', None)
assert hasattr(meta, 'keyed_list_serializer_field'), \
"Must provide a field name at keyed_list_serializer_field when using KeyedListSerializer"
self._keyed_field = meta.keyed_list_serializer_field
def to_internal_value(self, data):
# syntax is py3 only
data = [{**v, **{self._keyed_field: k}} for k, v in data.items()]
return super().to_internal_value(data)
def to_representation(self, data):
response = super().to_representation(data)
return {v.pop(self._keyed_field): v for v response}
对于Py2,您需要使super
调用显式并替换指示的字典构造函数。您可以通过将其分配给list_serializer_class
并选择一个keyed_list_serializer_field
(即用作dict键的字段)来使用它:
class MySerializer(ModelSerializer):
class Meta:
list_serializer_class = KeyedListSerializer
keyed_list_serializer_field = 'id'
keyed_list_serializer_field
应该包含唯一值;上面的实现没有检查。