如何在ViewSet @action方法上指定可选参数?

时间:2019-04-16 21:20:11

标签: python django django-rest-framework

我有一个ViewSet类,其方法如下:

@action(methods=["get"], detail=True, url_path="foo")
def foo(self, request: Request, pk: int) -> Response:
    limit = request.query_params.get("limit")
    if limit is not None:
        limit = int(limit)
    …

我想

  1. 声明方法,以便生成的OpenAPI规范记录此可选参数,
  2. 理想情况下,我不必手动弄出变量并对其进行转换。

像这样的事情会很理想:

def foo(self, _: Request, pk: int, limit: Optional[int] = None) -> Response:

但是它不起作用-limit始终是None


上述第1点的解决方案是对方法进行更多装饰:

@swagger_auto_schema(
    manual_parameters=[
        openapi.Parameter(
            "limit",
            openapi.IN_QUERY,
            required=False,
            type=openapi.TYPE_INTEGER
        )
    ]
)

1 个答案:

答案 0 :(得分:1)

To be able to do what you're after, you'd need to capture query string parameters in Django's url mapping, but Django only searches for request path there, and does not take query string parameters into consideration: docs (this goes all the way down to how django maps urls to views, before DRF and view sets come into play)

The only way I can think of to achieve what you want, is to provide limit as a path parameter, not a query string parameter. Then, you could capture limit from the request path and include it into the view method as a parameter, like this:

@action(methods=["get"], detail=True, url_path="foo(?:/(?P<limit>[0-9]+))?")
def foo(self, request: Request, pk: int, limit: Optional[int] = None) -> Response:
    ...