Routers
When using ViewSets, you don't need to design your URLs yourself. DRF routers automatically wire up your view logic to a set of URLs, making URL routing incredibly quick and consistent.
Using DefaultRouter
The DefaultRouter creates a standard set of RESTful routes.
python
# urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from . import views
# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'users', views.UserViewSet, basename='user')
router.register(r'articles', views.ArticleViewSet, basename='article')
# The API URLs are now determined automatically by the router.
urlpatterns = [
path('', include(router.urls)),
]Generated Routes
Registering router.register(r'users', UserViewSet) automatically generates the following URLs:
| URL | HTTP Method | Action |
|---|---|---|
/users/ | GET | list() |
/users/ | POST | create() |
/users/{pk}/ | GET | retrieve() |
/users/{pk}/ | PUT | update() |
/users/{pk}/ | PATCH | partial_update() |
/users/{pk}/ | DELETE | destroy() |
This significantly cuts down the boilerplate needed in your urls.py file!
