使用django rest framerwork将对象的列表作为字典返回并带有键作为对象id [英] Return list of objects as dictionary with keys as the objects id with django rest framerwork

查看:69
本文介绍了使用django rest framerwork将对象的列表作为字典返回并带有键作为对象id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Currently, I have a ListAPIView that returns a list of object dictionaries:

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

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

I would like to change this to be formatted as a dictionary with the id as the key:

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

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

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.

推荐答案

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

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}

这篇关于使用django rest framerwork将对象的列表作为字典返回并带有键作为对象id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆