DRF-Spectacular函数视图无法生成OpenApiParameter问题排查
问题原因与解决方案
问题出在函数视图的OpenApiParameter缺少显式的位置声明。DRF-Spectacular处理类视图时,会自动关联HTTP方法(如get)与查询参数的上下文,但处理函数视图时,必须明确指定参数的位置,否则框架无法识别这是一个URL查询参数。
修改后的函数视图代码
@api_view(["GET"]) @extend_schema( parameters=[ OpenApiParameter( name="jurisdiction", description="City for the query", required=True, type=str, default="Boston", location=OpenApiParameter.QUERY # 新增这一行,指定参数为查询参数 ), ], description='More descriptive text', responses={200: OpenApiTypes.OBJECT}, ) def distinct_address_autocomplete(request: Request): jurisdiction = request.GET.get("jurisdiction", "Boston") addresses = get_distinct_addresses(jurisdiction) filtered_addresses = addresses # 实现你的过滤逻辑 return Response(filtered_addresses)
原理说明
- 类视图的
get方法属于HTTP GET请求的上下文,DRF-Spectacular会自动将参数识别为查询参数,无需额外声明location。 - 函数视图仅通过
@api_view(["GET"])声明请求方法,但框架无法自动推断参数的传递位置,必须通过location=OpenApiParameter.QUERY明确告诉框架:这个参数是通过URL查询字符串传递的。
内容的提问来源于stack exchange,提问作者glitchwizard
相关产品推荐
相关产品推荐

