如何在ViewSet中为与标准操作相同的路由添加自定义PUT动作
解决方案
你只需要给custom_action方法加上DRF自带的@action装饰器,按如下配置参数即可:
from rest_framework.decorators import action class SomeViewSet(viewsets.ViewSet): def create(self, request): pass @action(detail=False, methods=['put'], url_path='') def custom_action(self, request): pass
参数说明
detail=False:标记该动作作用于资源集合路径(也就是你注册的根路径some-route/),而非单个资源的详情路径methods=['put']:指定该动作仅接收PUT类型的HTTP请求url_path='':将动作的路径后缀设为空,避免默认追加方法名custom_action到根路径后,最终匹配的路径和create动作完全一致
配置完成后,POST请求some-route/仍然走create方法,PUT请求some-route/会自动路由到custom_action方法。
内容的提问来源于stack exchange,提问作者Dmytro
相关产品推荐
相关产品推荐

