问题:DRF视图集中若想添加其他API?
通过给视图集中的函数,添加DRF的@action()装饰器
DRF的@action装饰器,用来为函数添加路由,主要参数有:
- methods:支持的请求方式,值为一个列表,默认为['GET']
- detail:布尔类型,表示是否为详细资源对象(即主键是否在url中,True表示是)
- url_path:指定url路由名称,默认为被action修饰的函数名
-
url_name:指定url名称,默认为被action修饰的函数名,内部操作用
注意:detail为必填参数,显示定义的路由优先级大于默认的
例1:detail=False
class MenuViewSet(BaseModelViewSet): """ 菜单管理API """ queryset = Menu.objects.all() serializer_class = MenuSerializer # 获取用户菜单/菜单按钮权限API # detail详情大意为是否需要传pk,若传为True,反之为False @action(methods=['GET'], detail=False, url_path='web_router') def xingchen(self, request): return ResponseOK(msg="获取成功")
例2:detail=True
class MenuViewSet(BaseModelViewSet): """ 菜单管理API """ queryset = Menu.objects.all() serializer_class = MenuSerializer @action(methods=['GET'], detail=True) def xc(self, request, pk): print('id', pk) return ResponseOK(msg="获取成功")TRANSLATE with x English TRANSLATE with COPY THE URL BELOW Back EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back 标签:--,detail,视图,url,API,action,DRF From: https://www.cnblogs.com/u-damowang1/p/16990699.html