How to use django-routing Routers-simplerouter-defaultrouter

Source: Internet
Author: User


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


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.