我有一个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)
…
我想
像这样的事情会很理想:
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
)
]
)
答案 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:
...