Automatic routing for the DRF, can be achieved for the ViewSet
classes.
Assume that the ViewSet class goes by the name of MyViewSet
for
this example.
To generate the routing of MyViewSet
, the SimpleRouter
will be utilized.
On myapp/urls.py
:
from rest_framework import routers
router = routers.SimpleRouter() # initialize the router.
router.register(r'myview', MyViewSet) # register MyViewSet to the router.
That will generate the following URL patterns for MyViewSet
:
^myview/$
with name myview-list
.^myview/{pk}/$
with name myview-detail
Finally to add the generated patterns in the myapp
's URL patterns, the django's include()
will be used.
On myapp/urls.py
:
from django.conf.urls import url, include
from rest_framework import routers
router = routers.SimpleRouter()
router.register(r'myview', MyViewSet)
urlpatterns = [
url(r'other/prefix/if/needed/', include(router.urls)),
]