Return list of objects as dictionary with keys as the objects id with django rest framerwork

前端 未结 2 797
暗喜
暗喜 2021-02-13 09:23

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

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

I would like to change

相关标签:
2条回答
  • 2021-02-13 09:53

    You can traverse each item and with a dict comprehension create your desired dictionary. For example:

    >>> 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}}
    
    0 讨论(0)
  • 2021-02-13 09:54

    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}
    
    0 讨论(0)
提交回复
热议问题