Routers
Introduction#
Routing is the process of mapping the logic (view methods etc.) to a set of URLs. REST framework adds support for automatic URL routing to Django.
Syntax#
- router = routers.SimpleRouter()
- router.register(prefix, viewset)
- router.urls # the generated set of urls for the registered viewset.
[Introductory] Basic usage, SimpleRouter
Automatic routing for the DRF, can be achieved for the ViewSet classes.
-
Assume that the ViewSet class goes by the name of
MyViewSetfor this example. -
To generate the routing of
MyViewSet, theSimpleRouterwill be utilized.
Onmyapp/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 namemyview-list.^myview/{pk}/$with namemyview-detail
-
Finally to add the generated patterns in the
myapp’s URL patterns, the django’sinclude()will be used.
Onmyapp/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)), ]