View component of drf

Routing component of drf

Quick configuration

Before the last blog, we all wrote routes by hand to configure URLs

# Common writing
path('books4/', views.Book4View.as_view()),
re_path('books4/(?P<pk>\d+)', views.Book4DetailView.as_view()),

# Inherited ViewSetMixin, add action
path('books5/', views.Book5View.as_view(actions={'get':'list','post':'create'})),
# When the path matches and it is a get request, the list method of Book5View will be executed
re_path('books5/(?P<pk>\d+)', views.Book5View.as_view(actions={'get':'retrieve','put':'update','delete':'destroy'})),

drf provides a method to automatically generate routes

  1. Import the routes module. There are two classes, SimpleRouter and DefaultRouter
  2. Instantiate class to get object
  3. register
  4. Router Get automatically generated routes in URLs (in list form)
  5. Add the generated routing list to urlpeers
# urls.py
from app01 import views
from rest_framework import routers
# Import router module
router = routers.SimpleRouter()
# Using one of the routers modules, simple routing
router.register('books',views.BookViewSet)
# Registration. The first parameter is filled with the suffix of url, which is equivalent to the regular matching in urlpatterns. The second parameter is to write the triggered attempt class (inheriting the ModelViewSet)
# Router The url will generate a list containing two URLs

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]
urlpatterns += router.urls
# Router url is spliced with urlpatterns to access the url
# views.py
class BookViewSet(ModelViewSet):
    # You need to inherit this class to automatically generate routes
    queryset = models.Book.objects
    serializer_class = ser.BookSerializer

In addition to SimpleRouter, there is also DefaultRouter. There will be four more URLs in the generated list. It also supports receiving similar URLs with a named packet format html json suffix

Use of action

After the route is automatically generated, the get and post methods in the view were completely encapsulated when we were writing APIView. If you need to use other view functions, you can also use action to extend them

  1. rest_framework.decorators import action

  2. In the view class that inherits the ModelViewSet, a decorator is written on the view function that needs to be added with a route

    @action(method=['GET',],detail=False)

  3. detail=False means that an address without pk is generated, =True means that a named packet is generated and a pk value is received

class BookViewSet(ModelViewSet):
# Need to inherit ModelViewSet
    queryset = models.Book.objects
    serializer_class = ser.BookSerializer

    @action(methods=['GET'],detail=False)
    # Methods can be recognized in both uppercase and lowercase
    # If detail is True, write one more formal parameter to receive pk value
    # The other writing method is the same as that of ordinary GenericAPIView, and the Response should be returned manually
    def bookAction(self,request):
        return Response({'msg':'action'})

Here you can see that a new ur has been added, where the suffix of the url is the function name of the view function

To sum up

A decorator provided by drf is placed above the decorated view function. Method is the request method. detail specifies whether to take pk parameters. The function name of the view function is used as the suffix of the url. We can use action to automatically generate routes for custom view functions

View inheritance relationship

The following are the inheritance relationships of some views

#Two base classes
APIView
GenericAPIView: For database operations, queryset and serializer_class


#5 view extension classes (rest_framework.mixins)
CreateModelMixin: create Method to create a
DestroyModelMixin: destory Method to delete a
ListModelMixin: list Method to get all
RetrieveModelMixin: retrieve Get one
UpdateModelMixin: update Modify one

#9 subclass view (rest_framework.genes)
CreateAPIView:inherit CreateModelMixin,GenericAPIView,have post Method, adding data
DestroyAPIView: inherit DestroyModelMixin,GenericAPIView,have delete Method, deleting data
ListAPIView: inherit ListModelMixin,GenericAPIView,have get Method to get all
UpdateAPIView: inherit UpdateModelMixin,GenericAPIView,have put and patch Methods, modifying data
RetrieveAPIView: inherit RetrieveModelMixin,GenericAPIView,have get Method to get a


ListCreateAPIView: inherit ListModelMixin,CreateModelMixin,GenericAPIView,have get Get all, post Method addition
RetrieveDestroyAPIView: inherit RetrieveModelMixin,DestroyModelMixin,GenericAPIView,have get Method to get one, delete Method delete
RetrieveUpdateAPIView: inherit RetrieveModelMixin,UpdateModelMixin,GenericAPIView,have get Get one, put,patch modify
RetrieveUpdateDestroyAPIView: inherit RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,GenericAPIView,have get Get one, put,patch Modification, delete delete

#View set
ViewSetMixin: Rewritten as_view 
ViewSet:      inherit ViewSetMixin and APIView

GenericViewSet: inherit ViewSetMixin, generics.GenericAPIView
ModelViewSet: inherit mixins.CreateModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,mixins.ListModelMixin,GenericViewSet
ReadOnlyModelViewSet: inherit mixins.RetrieveModelMixin,mixins.ListModelMixin,GenericViewSet

Tags: DRF

Posted by Deivas on Wed, 01 Jun 2022 08:21:19 +0530