I am using a custom ListSerializer to reformat a JSON response and it generates the proper format when I log from inside the serializer, but when it is returned to the ViewSet, the response becomes a list of the dictionary keys rather than including the entire dictionary with both keys and values.
I have made a simplified example of the problem with hard-coded JSON to illustrate what I believe to be the crux of the issue.
views.py
class ElementViewSet(viewsets.ViewSet):
...
@detail_route(methods=['get'])
def elements(self, request, pk=None):
elements = ElementFilterSet(params)
serializer = serializers.ElementSerializer(elements, many=True)
return Response(serializer.data)
serializers.py
class ElementListSerializer(serializers.ListSerializer):
def to_representation(self, obj):
result = {"home": {"label_color": "#123456","label_text": "young"},"speak": { "label_color": "","label_text": "Hello"}}
return result
class ElementSerializer(serializers.ModelSerializer):
class Meta:
model = Element
list_serializer_class = ElementListSerializer
def to_representation(self, obj):
result = super(ElementSerializer, self).to_representation(obj)
return result
The response I get is a list of dictionary keys:
[
"speak",
"home"
]
rather than what I want, which is the entire dictionary (in this case, simply the hard-coded JSON result):
{
"home": {
"label_color": "#123456",
"label_text": "young"
},
"speak": {
"label_color": "",
"label_text": "Hello"
}
}
I am new to customizing serializers and using list_serializer_class; I likely simply don't understand how they work, but this behavior does seem unexpected to me.