django-restframework serialize relations as dictionaries rather then arrays
It is possible by overriding the list serializers and setting list_serializer_class
for each serializer that requires it, as I suggested in this answer.
Of course, you will need to adapt it slightly:
class <YourClass>ListSerializer(serializers.ListSerializer): def to_representation(self, data): r = super().to_representation(data) return { item['<key_field>']: item for item in r }
@Michael Rigonis answer (https://stackoverflow.com/a/45238191/270265) was the key to success. I had to tweak it a little, so I was able to use it for the top level as well.:
class DictSerializer(serializers.ListSerializer): key = None def __init__(self, *args, **kwargs): self.key = kwargs.pop('key', self.key) super().__init__(*args, **kwargs) def to_representation(self, data): r = super().to_representation(data) return {item[self.key]: item for item in r} @property def data(self): # This is a bit nasty, because the only "Many-Serializer" is a ListSerializer we inherit of it, # but when converting it to json we call the BaseSerializer directly, because we want a Dictionary rather then a list ret = super(serializers.ListSerializer, self).data return ReturnDict(ret, serializer=self)