如何从 drf-spectacular API 文档中删除 RetrieveUpdateAPIView 中的 put 方法?

How to remove put method in RetrieveUpdateAPIView from drf-spectacular API documentation?

我有以下看法:

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,它在文档中向我展示了我们在 API 中不需要的 PUT 方法。我的问题是,如何自定义 drf-spectacular 以在文档中不包含 PUT 方法?

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

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)

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

@extend_schema(methods=['PUT'], exclude=True)