在使用DRF视图集时,往往需要配一大堆路由,例如:
# views.py class DepartmentViewSet(ListModelMixin,CreateModelMixin,RetrieveModelMixin, UpdateModelMixin,DestroyModelMixin,GenericViewSet): queryset = Department.objects.all() serializer_class = DepartmentSerializer # urls.py urlpatterns = [ url(r'^departments$',views.DepartmentViewSet.as_view({'get':'list','post':'create'})), url(r'^departments/(?P<pk>d+)$',views.DepartmentViewSet.as_view({ 'get':'retrieve','put':'update','delete':'destroy' })) ]
实在是太麻烦了。
幸好DRF提供了两个router可以很方便地设置路由:
- SimpleRouter
- DefaultRouter
这两个router的使用方法都是一样的,只不过DefaultRouter多点功能,例如可以访问(url+.json)取得返回的JSON数据,访问首页也可以知道有多少个类视图......
-
使用方法
1.创建router对象,并注册视图集。
from rest_framework import routers from user.views import DepartmentViewSet router = routers.SimpleRouter() router.register(r'department',DepartmentViewSet,base_name='dep')
register(prefix, viewset, base_name)方法说明:
- prefix 该视图集的路由前缀
- viewset 视图集
- base_name 路由名称的前缀
2.添加路由数据
可以有两种方式:
urlpatterns = [ ... ] urlpatterns += router.urls
或者
urlpatterns = [
...
url(r'^', include(router.urls))
]
3.验证
打印一下urlpatterns,会发现自动生成了~
[<RegexURLPattern dep-list ^department/$>,
<RegexURLPattern dep-detail ^department/(?P<pk>[^/.]+)/$>]