返回对象列表作为字典,键作为对象id与django rest framerwork

roo*_*oob 11 python api django dictionary django-rest-framework

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

[
  { id: 1, ...},
  { id: 2, ...},
  ...
]
Run Code Online (Sandbox Code Playgroud)

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

{
  "1": { id: 1, ...},
  "2": { id: 2, ...},
  ...
}
Run Code Online (Sandbox Code Playgroud)

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

Jun*_*sor 5

您可以遍历每个项目并使用字典理解创建您想要的字典。例如:

>>> 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}}
Run Code Online (Sandbox Code Playgroud)


soo*_*oot 5

我想你可以to_representation在你的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}
Run Code Online (Sandbox Code Playgroud)