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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:45:02