Issue
I currently have two different class based views for detailing a specific object and for listing all objects:
class StatusList(ListAPIView):
permission_classes = (IsAuthenticated,)
serializer_class = serializers.StatusSerializer
def get_queryset(self):
queryset = helperfunctions.getObjects(self.request.user, models.Status)
return queryset
class StatusDetail(RetrieveAPIView):
permission_classes = (IsAuthenticated,)
serializer_class = serializers.StatusSerializer
def get_queryset(self):
queryset = helperfunctions.getObjects(self.request.user, models.Status)
return queryset
Note that helperfunctions.getObjects() simply returns the objects that share the same establishment with the user, so that they can’t see statuses that they shouldn’t.
What I want to know is whether there’s an option to use only one class based view for both StatusDetail and StatusList, which would automatically know that when it gets a pk in the get request it returns the appropriate object, and when it doesn’t, it should return the whole list of objects.
Thanks for any help 🙂
Solution
Use viewsets, like so
:
from rest_framework import viewsets, permissions, mixins
class StatusDetail(mixins.ListModelMixin, #specify wanted mixins
mixins.RetrieveModelMixin,
viewsets.GenericViewSet):
permission_classes = (IsAuthenticated,)
serializer_class = serializers.StatusSerializer
def get_queryset(self):
queryset = helperfunctions.getObjects(self.request.user, models.Status)
return queryset
Answered By – idik
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0