1

我有以下看法:

class PersonalInfos(generics.RetrieveUpdateAPIView):
    serializer_class = ClientSerializer
    permission_classes = [IsAuthenticated]
    def get_queryset(self):
        """
        :return: A QuerySet Object
        """
        return Client.objects.get(user=self.request.user)

    def get(self, *args):
        """
        :param args: Handled by rest_framework views.dispatch

        :return: JSON object containing User Personal Data
        """
        queryset = self.get_queryset()
        serializer = ClientSerializer(queryset)
        return Response(data=serializer.data)

    def patch(self, request):
        """
        :param request: request object is sent by the client

        :return:  Json response with the data sent of the body
        """

        client = self.get_queryset()
        serializer = ClientSerializer(client, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(data=serializer.data, status=200)
        return Response(data="Unexpected Parameters", status=400)

视图中一切正常,但问题是我正在使用 drf-spectacular,它在文档中向我展示了一个 PUT 方法,我们在 API 中不需要。我的问题是,如何自定义 drf-spectacular 在文档中不包含 PUT 方法?

在此处输入图像描述

4

2 回答 2

5

您可以使用@extend_schema装饰器从生成的模式中排除一个或多个方法,如下所示。

@extend_schema(methods=['PUT'], exclude=True)
于 2021-08-09T08:09:25.420 回答
0

RetrieveAPIView我使用代替解决了这个问题,UpdateRetrieveAPIView并且我已经扩展了它以包含一个 PATCH 方法。RetrieveAPIView将完美地处理 PATCH 方法,并且不会在 API 文档中自动显示 UPDATE 请求。这是新代码:

class PersonalInfos(generics.RetrieveAPIView):
    serializer_class = ClientSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        """
        :return: A QuerySet Object
        """
        return Client.objects.get(user=self.request.user)

    def get(self, *args):
        """
        :param args: Handled by rest_framework views.dispatch

        :return: JSON object containing User Personal Data
        """
        queryset = self.get_queryset()
        serializer = ClientSerializer(queryset)
        return Response(data=serializer.data)

    def patch(self, request):
        """
        :param request: request object is sent by the client

        :return:  Json response with the data sent of the body
        """

        client = self.get_queryset()
        serializer = ClientSerializer(client, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(data=serializer.data, status=200)
        return Response(data="Unexpected Parameters", status=400)
于 2021-03-25T09:38:52.693 回答