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.
- Created a review model and applied migrations
- created the review serializer
- 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.
pipenv install drf-nested-routersThen you import its routers in your urls.py file
from rest_framework_nested import routersNow 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 pathfrom rest_framework_nested import routersfrom . import views
router = routers.DefaultRouter() # parent routerrouter.register('products', views.ProductViewSet)router.register('collections', views.CollectionViewSet)
products_router = routers.NestedDefaultRouter(router, 'products', lookup='product') # nested routerproducts_router.register('reviews', views.ReviewViewSet, basename='product-reviews') # registering our child resource
# URLConfurlpatterns = router.urls + products_router.urls # combine the parent and child urls into the urlpatterns array