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

drf_yasg手动定义路径参数报错:either schema or type are required

解决drf_yasg路径参数类型识别错误及手动定义参数的问题

错误原因

手动定义openapi.Parameter时,必须明确指定参数的类型(type)或模式(schema),二者选其一,不能同时设置也不能都不设置。你当前的代码缺少这个关键配置,因此触发了either schema or type are required for Parameter object (not both)!错误。

解决方案1:通过type参数指定整数类型

直接在openapi.Parameter中添加type=openapi.TYPE_INTEGER,明确参数为整数类型:

@swagger_auto_schema(
    method='PATCH',
    manual_parameters=[
        openapi.Parameter(
            'object_id', 
            openapi.IN_PATH, 
            required=True, 
            description='Object ID',
            type=openapi.TYPE_INTEGER  # 指定参数为整数类型
        ),
        # 其他查询参数
    ],
    # 其他配置:operation_description, responses等
)
@api_view(['PATCH'])
@permission_classes([IsAuthenticated])
def function(request, object_id):
    # 视图逻辑代码
    pass

解决方案2:通过schema参数定义类型(支持复杂场景)

使用openapi.Schema来定义参数类型,这种方式更灵活,适合需要额外约束(比如范围、格式)的场景:

@swagger_auto_schema(
    method='PATCH',
    manual_parameters=[
        openapi.Parameter(
            'object_id', 
            openapi.IN_PATH, 
            required=True, 
            description='Object ID',
            schema=openapi.Schema(type=openapi.TYPE_INTEGER)  # 用schema指定整数类型
        ),
        # 其他查询参数
    ],
    # 其他配置:operation_description, responses等
)
@api_view(['PATCH'])
@permission_classes([IsAuthenticated])
def function(request, object_id):
    # 视图逻辑代码
    pass

额外提示

如果不想手动定义路径参数,也可以尝试将drf_yasg升级到最新版本——部分旧版本存在Django路径转换器(如<int:)识别不准确的问题,升级后可能自动将object_id识别为整数类型,无需手动配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 03:52:05