Using Routers
Because we're using ViewSet
classes rather than View
classes, we actually don't need to design the URL conf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using a Router
class. All we need to do is register the appropriate view sets with a router, and let it do the rest.
Here's our re-wired snippets/urls.py
file.
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from snippets import views
# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'snippets', views.SnippetViewSet)
router.register(r'users', views.UserViewSet)
# The API URLs are now determined automatically by the router.
urlpatterns = [
path('', include(router.urls)),
]
Registering the viewsets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the viewset itself.
The DefaultRouter
class we're using also automatically creates the API root view for us, so we can now delete the api_root
method from our views
module.
当前内容版权归 Django REST 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 Django REST .