Django rest framework returns the following output at an API endpoint
[
{
"id": "QFELD_2.3.2.QF1",
"siteuxid": "VBKM02_Abschlusstest",
"section": 2,
"maxpoints": 4,
"intest": true,
"uxid": "KA0",
"points": 0,
"value": 0,
"rawinput": "",
"state": 3
},
{
"id": "QFELD_2.3.2.QF2",
"siteuxid": "VBKM02_Abschlusstest",
"section": 2,
"maxpoints": 4,
"intest": true,
"uxid": "KA1",
"points": 0,
"value": 0,
"rawinput": "",
"state": 3
},
...
Is it possible to return the data in an list object format like:
{
"QFELD_2.3.2.QF1" : {
"siteuxid": "VBKM02",
"section": 2,
"maxpoints": 4,
"intest": true,
"uxid": "KA0",
"points": 0,
"value": 0,
"rawinput": "",
"state": 3
},
"QFELD_2.3.2.QF2" : {
"siteuxid": "VBKM02",
"section": 2,
"maxpoints": 4,
"intest": true,
"uxid": "KA1",
"points": 0,
"value": 0,
"rawinput": "",
"state": 3
},
...
My Serializer is:
class ScoreSerializer(serializers.ModelSerializer):
id = serializers.CharField(required=False, allow_blank=True, max_length=100, source='q_id')
class Meta:
model = Score
fields = ('id', 'siteuxid', 'section', 'maxpoints', 'intest', 'uxid', 'points', 'value', 'rawinput', 'state')
And View is:
class ScoreViewSet(viewsets.ModelViewSet):
serializer_class = ScoreSerializer
The ListMixin
code a is good place to get started. You should get the serializer's result and transform it as you like.
class ListModelMixin(object):
"""
List a queryset.
"""
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
# Might need to change this not to transform all the data
data = {i['id']: i for i in serializer.data}
return self.get_paginated_response(data)
serializer = self.get_serializer(queryset, many=True)
data = {i['id']: i for i in serializer.data}
return Response(data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With