Django-DRF Components learning - learning route

1. Route router

For views Viewset set, we can in addition to manually correspondence between the operation and action specified in the request mode, but also can help us to quickly Routers use routing information.

REST framework provides two router

  • SimpleRouter

  • DefaultRouter

1.1 Use

1) Create a router object and registered view set, for example,

from rest_framework import routers
​
router = routers.DefaultRouter()
router.register(r'router_stu', StudentModelViewSet, base_name='student')

register(prefix, viewset, base_name)

  • The prefixes prefix viewset

  • viewset set of views

  • Base_name routing prefix aliases

The routing code described above is formed as follows:

^books/$    name: book-list
^books/{pk}/$   name: book-detail

2) adding routing data

There are two ways:

urlpatterns = [
    ...
]
urlpatterns += router.urls

或
urlpatterns = [
    ...
    url(r'^', include(router.urls))
]

Routing sets used to view the generated routing address

 
 
from rest_framework.viewsets import ModelViewSet,ReadOnlyModelViewSet
class StudentModelViewSet(ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentModelSerializer
​
    def login(self,request):
        """学生登录功能"""
        print(self.action)
        return Response({"message":"登录成功"})

Routing Code:

 
 
from django.urls Import path, re_path
 from . Import views 
the urlpatterns = [ 
    ... 
] 
"" " Use drf provide Routing router to generate a routing list View Set " "" 
# instantiated Routing 
# drf provided a total of two to provide routing class for our use, consistent with their usage, function almost the same 
from rest_framework.routers Import defaultrouter 
Router = defaultrouter () 
# registered view set 
# router.register ( "routing prefix", set category view) 
router.register ( " router_stu " , views.StudentModelViewSet) 
#Append the generated routing table to the urlpatterns 
Print (router.urls) 
the urlpatterns + = router.urls
The above code successfully generated the routing address of the [add / delete / change / check a / the plurality of search functions], but we are not automatically customize the view route set method.

So if we have to generate custom routing method, you need to declare action action.

1.2 centralized view additional action statement

In view of the focus, if you want to help us let Router automatically generate routing information for a custom action, you need to use rest_framework.decorators.actiona decorator.

In action decorator decoration method name will be the name of the action as the action, the list, retrieve equivalents.

Decorative action may receive two parameters:

  • Methods : declare the action corresponding to the request method, a list of transfer

  • detail

    : Declare the action whether the path corresponding to a single resource, and whether it is

    xxx / <pk> / action method name /
    • True represents the path format isxxx/<pk>/action方法名/

    • It represents the path format is Falsexxx/action方法名/

For example:

from rest_framework.viewsets Import ModelViewSet
 from rest_framework.decorators Import Action 
class StudentModelViewSet (ModelViewSet): 
    QuerySet = Student.objects.all () 
    serializer_class = StudentModelSerializer 
    # Methods http request provided the current method which allows access to the current view Method 
    # Detail the current view whether the operation is a data 
    # Detail is True, indicates the path name format be router_stu /} {PK / Login / 
    @Action (methods = [ ' GET ' ], Detail = True)
     DEF Login (Self, Request, PK):
         "" " Log"" " 
        ... 
    # the Detail to False indicates the path name format should be router_stu / get_new_5 / 
    @Action (Methods = [ ' PUT ' ], the Detail = False)
     DEF get_new_5 (Self, Request):
         " "" to obtain the latest add the five student information "" " 
        ...

Automatically by the router node view for this method of forming a customized set of action would be the following:

^router_stu/get_new_5/$    name: router_stu-get_new_5
^router_stu/{pk}/login/$   name: router_stu-login

1.3 URL routing router formation of the way

1) SimpleRouter

SimpleRouter

2)DefaultRouter

DefaultRouter

DefaultRouter and SimpleRouter difference is, DefaultRouter will be more comes with a default root view of the API returns data in response to a hyperlink that contains a list of all views.

ok

Guess you like

Origin www.cnblogs.com/gbq-dog/p/10990865.html