You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

禁用DRF ViewSet方法后Swagger仍显示对应接口

解决DRF ViewSet禁用List/Retrieve后Swagger仍显示接口的问题

直接重写方法返回403没用,因为Swagger是靠检测ViewSet的注册action、允许的HTTP方法来生成文档的,重写逻辑不影响文档生成。给你几个靠谱的解决办法:

方法一:直接限制ViewSet允许的HTTP方法

在你的ViewSet类里添加http_method_names属性,把GET方法排除掉——毕竟List和Retrieve都是基于GET请求的:

class YourModelViewSet(viewsets.ModelViewSet):
    queryset = YourModel.objects.all()
    serializer_class = YourModelSerializer
    # 只保留需要的HTTP方法,去掉GET
    http_method_names = ['post', 'put', 'patch', 'delete']

这样DRF本身会直接拒绝GET请求,Swagger也不会生成对应的List/Retrieve接口文档。

方法二:用Swagger扩展装饰器排除指定Action

如果用的是drf-spectacular(现在主流的DRF Swagger工具),直接给ViewSet加@extend_schema装饰器,指定要排除的action:

from drf_spectacular.utils import extend_schema

@extend_schema(exclude=['list', 'retrieve'])
class YourModelViewSet(viewsets.ModelViewSet):
    queryset = YourModel.objects.all()
    serializer_class = YourModelSerializer
    # 这里如果重写了list/retrieve也没关系,装饰器会直接从文档里删掉它们

要是用的是旧版的drf-yasg,就给对应的方法加@swagger_auto_schema(auto_schema=None):

from drf_yasg.utils import swagger_auto_schema

class YourModelViewSet(viewsets.ModelViewSet):
    queryset = YourModel.objects.all()
    serializer_class = YourModelSerializer

    @swagger_auto_schema(auto_schema=None)
    def list(self, request, *args, **kwargs):
        return Response(status=status.HTTP_403_FORBIDDEN)

    @swagger_auto_schema(auto_schema=None)
    def retrieve(self, request, *args, **kwargs):
        return Response(status=status.HTTP_403_FORBIDDEN)

方法三:自定义ViewSet,不继承ModelViewSet

如果你的ViewSet本来就不需要List/Retrieve,直接继承GenericViewSet+需要的mixins,比如只继承CreateModelMixin、UpdateModelMixin、DestroyModelMixin:

from rest_framework import viewsets, mixins

class YourModelViewSet(mixins.CreateModelMixin,
                       mixins.UpdateModelMixin,
                       mixins.DestroyModelMixin,
                       viewsets.GenericViewSet):
    queryset = YourModel.objects.all()
    serializer_class = YourModelSerializer

这种方式从根源上就没有List和Retrieve的action,Swagger自然不会生成对应的文档。

内容的提问来源于stack exchange,提问作者Daniel Ramos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 08:42:10