A
A
Alexander Nesterov2021-12-10 17:16:55
Django
Alexander Nesterov, 2021-12-10 17:16:55

How to split get requests to get all objects and a specific one in APIView?

In most cases, you need to get a list of all faculties:

class FacultyView(APIView):
    def get(self, request):
        faculties = Faculty.objects.all()
        serializer = FacultySerializer(
            instance=faculties,
            many=True
        )
        return Response(serializer.data)

However, in some cases, you need to select a specific faculty to display detailed data. and for this you will have to create a separate class / view. Are there more optimal solutions that do not produce entities?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2021-12-10
@AlexNest

To do this, viewsets came up with:

class FacultyViewSet(
    mixins.ListModelMixin,
    mixins.RetrieveModelMixin,
    GenericViewSet
):
    queryset = Faculty.objects.all()
    serializer_class = FacultySerializer
    permission_classes = (permissions.AllowAny, )

It will display a list, and in detail, and without the boilerplate given by you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question