Now when we use a viewset, we are not going to explicitly register these url_patterns like below
urlpatterns = [ path('products/', views.ProductList.as_view()), path('products/<int:pk>/', views.ProductDetail.as_view()), path('collections/', views.CollectionList.as_view()), path('collections/<int:pk>/', views.CollectionDetail.as_view(), name='collection-detail')]That is what Routers are for, so what we do is that we register our viewsets with a Router and the Router will take care of generating these url_patterns for us
First import the Router from drf routers, and then create an instance of the Router class, and then register your urls wit the instance you just created. When registering, you provide two parameters, the first one is the endpoint(without the forward slash) and the second one is the ViewSet you want to handle that endpoint. see below
from rest_framework.routers import SimpleRouter
router = SimpleRouter()router.register('products', view.ProductViewSet)router.register('collections', view.CollectionViewSet)router.urls # this is where all our url patterns are gonna be stored. they are all managed by the router. you can pprint the router.urls to see how the url patterns are structured
''' because of what we've done above, we dont have any explicit urlpatterns in our urls.py file, so we can go ahead and set url patterns = router.urls(since we will get an error if our urls.py doesnt contain the url patterns)'''urlpatterns = router.urlsNow what if we have some specific patterns in our urlpatterns array, in that case we dont want to set urlpatterns to router.urls but rather we can use the path function to include urls from another place. see below
urlpatterns = [ path('', include(router.urls)), '''now you can specify other urls in here''']There is another router called DefaultRouter that we can use, that one has two extra features than the SimpleRouter. The first one is that when you go to the root url of your project (127.0.0.1:8000/store/), it will display all the endpoints available in your project. the second one is that when you append json to an endpoint (127.0.0.1:8000/store/products.json) it will retrieve all objects in json format. see below
from django.urls import pathfrom rest_framework.routers import DefaultRouterfrom . import views
router = DefaultRouter()router.register('products', views.ProductViewSet)router.register('collections', views.CollectionViewSet)
# URLConfurlpatterns = router.urls