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

如何使用drf-yasg Swagger手动自定义DRF视图的参数?

drf-yasg自定义参数不生效解决方案
  • 第一步:清理缓存并重启服务
    drf-yasg默认会缓存生成的Schema文档,开发环境下如果开启了缓存会导致修改不生效。可以先在settings.py中关闭swagger缓存:
SWAGGER_SETTINGS = {
    'DEFAULT_INFO': 'your_project.urls.swagger_info',
    'USE_SESSION_AUTH': False,
    # 新增以下配置关闭缓存
    'SCHEMA_CACHE_TIMEOUT': 0
}

修改后重启Django服务,刷新Swagger页面查看是否生效。

  • 第二步:确认装饰器挂载的方法与HTTP请求匹配
    你当前给retrieve方法加的装饰器,只会作用于GET详情请求(即带ID参数的GET请求)。如果你需要给PUT/PATCH请求加参数,需要给对应的update/partial_update方法单独加装饰器;如果需要避免方法绑定错误,也可以用method_decorator挂载到类上,指定需要生效的HTTP方法:
from django.utils.decorators import method_decorator

@method_decorator(name='retrieve', decorator=swagger_auto_schema(
    manual_parameters=[openapi.Parameter('test', openapi.IN_QUERY, description="test manual param", type=openapi.TYPE_BOOLEAN)]
))
class MyCustomView(RetrieveUpdateAPIView):
    ...
    def retrieve(self, request, *args, **kwargs):
        ...
  • 第三步:检查导入依赖是否正确
    确认你导入的openapi和swagger_auto_schema来自正确的包:
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
  • 第四步:强制指定接口操作ID(可选)
    如果上述步骤都无效,可以在swagger_auto_schema中添加operation_id参数强制绑定接口,避免自动生成的操作ID冲突导致配置失效:
@swagger_auto_schema(
    operation_id="my_custom_retrieve",
    manual_parameters=[openapi.Parameter('test', openapi.IN_QUERY, description="test manual param", type=openapi.TYPE_BOOLEAN)]
)
def retrieve(self, request, *args, **kwargs):
    ...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:00:03