Skip to content
thesarfo

Note

Nested Routers

Using drf-nested-routers to build a reviews-under-products endpoint with NestedDefaultRouter.

views 0

Now we want to go ahead and build the reviews api. Such that we can get all the reviews of a particular product. (127.0.0.1/8000/store/products/1/reviews) or we can get a single review of a particular product. ((127.0.0.1/8000/store/products/1/reviews/1)).

Now if you look at the endpoint for the reviews, you will see that we have nested resources(ie products and reviews). Now because we have nested resources, we have to talk about nested routers.

This note will assume that we have already built the Reviews api, ie.

  1. Created a review model and applied migrations
  2. created the review serializer
  3. created a view for the serializer

Then we go ahead to register the route.

Now, there is a github repository that talks about the installation and usage of nested routers in django rest framework.

To use it, you first have to install it.

Terminal window
pipenv install drf-nested-routers

Then you import its routers in your urls.py file

from rest_framework_nested import routers

Now this routers you just import also comes with its own classes like DefaultRouter, NestedDefaultRouter etc. so we need to create an instance of the DefaultRouter, and then register our parent route with its view set. Then we go ahead to register the child router with the parent router.

When registering our child router, we pass 3 args to the method, the parent router, parent prefix and lookup type see below

When registering our child router, we give it 3 args, the child prefix, viewset and the basename (used as a prefix for generating the name of the url patterns)

from django.urls import path
from rest_framework_nested import routers
from . import views
router = routers.DefaultRouter() # parent router
router.register('products', views.ProductViewSet)
router.register('collections', views.CollectionViewSet)
products_router = routers.NestedDefaultRouter(router, 'products', lookup='product') # nested router
products_router.register('reviews', views.ReviewViewSet, basename='product-reviews') # registering our child resource
# URLConf
urlpatterns = router.urls + products_router.urls # combine the parent and child urls into the urlpatterns array