Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework : Do not return array but list of objects with id as key

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
like image 512
niklas Avatar asked Oct 05 '16 15:10

niklas


1 Answers

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)
like image 73
Linovia Avatar answered Sep 21 '22 04:09

Linovia