路由的两种写法
只要继承了ViewSetMixin,路由的配置就发生变化了,需要映射
方式一(手动配置)
urls.py
urlpatterns = [
# path('books_set/', views.BookSetView.as_view()), # 直接报错
path('books_set/', views.BookSetView.as_view({'get':'list','post':'create'})),
re_path('^books_set/(?P<pk>\d+)', views.BookSetView.as_view({'get':'retrieve','put':'update','delete':'destroy'})),
]
方式二(自动生成)
from rest_framework import routers
router = routers.SimpleRouter()
router.register('books', views.BookSetView, basename='book')
urlpatterns += router.urls
action装饰器
作用
在视图集中自定义的方法生成路由
参数
methods
:请求方式detaill
:路径是否与单一资源对应
使用
views.py
from rest_framework.decorators import action
class PublishView(ViewSet):
@action(methods=['post',], detail=False, url_path='cc', url_name='cc')
def cc(self, request):
return Response('6666666')
urls.py
urlpatterns = [
path('books_all/', views.BookView.as_view({'post': 'cc'}))
]