Routing routers
For view set Viewset, we can also use routers to help us quickly implement routing information in addition to manually indicating the correspondence between the request mode and action action.
The REST framework provides two router
- Simplerouter
- Defaultrouter
1. How to use
1) Create the Router object and register the view set, for example
from rest_framework import routers
router = routers.SimpleRouter()
router.register(r‘books‘, BookInfoViewSet, base_name=‘book‘)
register(prefix, viewset, base_name)
- Prefix the route prefix for this view set
- Viewset View Set
- Base_name prefix for route names
As the above code will form the following routes:
^books/$ name: book-list
^books/{pk}/$ name: book-detail
2) Add route data
There are two ways of doing this:
urlpatterns = [
...
]
urlpatterns += router.urls
Or
urlpatterns = [
...
url(r‘^‘, include(router.urls))
]
2. The view set contains an additional action
class BookInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
queryset = BookInfo.objects.all()
serializer_class = BookInfoSerializer
@action(methods=[‘get‘], detail=False)
def latest(self, request):
...
@action(methods=[‘put‘], detail=True)
def read(self, request, pk):
...
The route formed by this view assembly:
^books/latest/$ name: book-latest
^books/{pk}/read/$ name: book-read
3. Route router how URLs are formed
1) Simplerouter
2) Defaultrouter
The difference between Defaultrouter and Simplerouter is that Defaultrouter comes with a default API root view that returns a hyperlink response data that contains all the list views.
How to use django-routing Routers-simplerouter-defaultrouter