在之前进行drf开发时,对于路由我们一般进行两种配置:
视图继承APIView
from django.urls import path
from app01 import views
urlpatterns = [
path('api/users/', views.UserView.as_view()),
]
视图继承 ViewSetMixin
(GenericViewSet、ModelViewSet)
对于这种形式的路由,drf中提供了更简便的方式:
from django.urls import path, re_path, include
from app01 import views
urlpatterns = [
path('api/users/', views.UserView.as_view({"get":"list","post":"create"})),
path('api/users/<int:pk>/', views.UserView.as_view({"get":"retrieve","put":"update","patch":"partial_update","delete":"destory"})),
]
对于这种形式的路由,drf中提供了更简便的方式:
from rest_framework import routers
from app01 import views
router = routers.SimpleRouter()
router.register(r'api/users', views.UserView)
urlpatterns = [
# 其他URL
# path('xxxx/', xxxx.as_view()),
]
urlpatterns += router.urls
路由分组:也可以利用include,给URL加前缀
from django.urls import path, include
from rest_framework import routers
from app01 import views
router = routers.SimpleRouter()
router.register(r'users', views.UserView)
urlpatterns = [
# path('api/', include((router.urls, 'app_name')) # 简写
path('api/', include((router.urls, 'app_name'), namespace='instance_name')),
]