myModelViewSet.py 1.38 KB
Newer Older
1
from .myModelSerializer import MyModelSerializer
Florent Chehab's avatar
Florent Chehab committed
2
from backend_app.permissions import DEFAULT_VIEWSET_PERMISSIONS
Florent Chehab's avatar
Florent Chehab committed
3
from rest_framework import viewsets
4 5


Florent Chehab's avatar
Florent Chehab committed
6
class MyModelViewSet(viewsets.ModelViewSet):
7
    serializer_class = MyModelSerializer
8
    permission_classes = DEFAULT_VIEWSET_PERMISSIONS
9

Florent Chehab's avatar
Florent Chehab committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
    LIST_SHOULD_BE_DETAIL = False

    def list(self, request, *args, **kwargs):
        response = super(viewsets.ModelViewSet, self).list(  # pylint: disable=E1003
            request, *args, **kwargs
        )  # call the original 'list'

        if self.LIST_SHOULD_BE_DETAIL:
            if len(response.data) == 0:
                response.data = dict()
            elif len(response.data) == 1:
                response.data = response.data[0]
            else:
                raise Exception(
                    "There should be no more than one element in the queryset, check it !"
                )

        return response

29 30 31 32 33
    def get_queryset(self):
        """
        Extended default rest framework behavior
        to prefetch some table and enhance performances
        """
34
        self.my_model_queryset = self.queryset.prefetch_related(
35 36
            "moderated_by", "updated_by", "pending_moderation"
        )
37 38 39 40 41 42
        return self.extend_queryset()

    def extend_queryset(self):
        """
        Function to extend get_queryset when subclassing
        """
43
        return self.my_model_queryset