DictModeViewSet.py 674 Bytes
Newer Older
1
2
3
4
5
6
7
8
from rest_framework import viewsets


class DictModeViewSet(viewsets.ModelViewSet):
    """
    ViewSet that renders data as dict with keys corresponding to the model
    primary key. Instead of list.
    """
9
    BYPASS_DICT_MODE = False
10
11
12
13

    def list(self, request, *args, **kwargs):
        response = super(viewsets.ModelViewSet, self).list(  # pylint: disable=E1003
            request, *args, **kwargs)  # call the original 'list'
14
15
16
17
18
        if not self.BYPASS_DICT_MODE:
            pk_attr_name = self.serializer_class.Meta.model._meta.pk.name
            response.data = {
                d[pk_attr_name]: d for d in response.data
            }
19
        return response