在之前进行drf开发时,对于路由我们一般进行两种配置:

视图继承APIView

  1. from django.urls import path
  2. from app01 import views
  3. urlpatterns = [
  4. path('api/users/', views.UserView.as_view()),
  5. ]

视图继承 ViewSetMixin

(GenericViewSet、ModelViewSet)
对于这种形式的路由,drf中提供了更简便的方式:

  1. from django.urls import path, re_path, include
  2. from app01 import views
  3. urlpatterns = [
  4. path('api/users/', views.UserView.as_view({"get":"list","post":"create"})),
  5. path('api/users/<int:pk>/', views.UserView.as_view({"get":"retrieve","put":"update","patch":"partial_update","delete":"destory"})),
  6. ]

对于这种形式的路由,drf中提供了更简便的方式:

  1. from rest_framework import routers
  2. from app01 import views
  3. router = routers.SimpleRouter()
  4. router.register(r'api/users', views.UserView)
  5. urlpatterns = [
  6. # 其他URL
  7. # path('xxxx/', xxxx.as_view()),
  8. ]
  9. urlpatterns += router.urls


路由分组:也可以利用include,给URL加前缀

  1. from django.urls import path, include
  2. from rest_framework import routers
  3. from app01 import views
  4. router = routers.SimpleRouter()
  5. router.register(r'users', views.UserView)
  6. urlpatterns = [
  7. # path('api/', include((router.urls, 'app_name')) # 简写
  8. path('api/', include((router.urls, 'app_name'), namespace='instance_name')),
  9. ]