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.
EDIT: current version available in a Github project and PYPI (
pip install drf-keyed-list
)Here's a general-purpose class that is bi-directional (vs. the read-only implementation above):
For Py2, you need to make the
super
calls explicit and replace the indicated dictionary constructor. You use it by assigning it to yourlist_serializer_class
and selecting akeyed_list_serializer_field
(i.e. the field used as the dict key):The
keyed_list_serializer_field
should contain unique values; the above implementation doesn't check.I think you can implement the
to_representation
function in your Serializer.You can traverse each item and with a dict comprehension create your desired dictionary. For example: