drf framework - View family | GenericAPIView | mixins | generics | viewsets

View family

view: View 
generics: view tool 
mixins: View toolset 
viewsets: View Set 
learning curve: APIView => GenericAPIView => as mixins five tools => = generics view of the tool> viewsets of view set

 

A base class .GenericAPIView

# GenericAPIView inherited APIView fully compatible APIView 
# Key: GenericAPIView done what things APIView based on? 
1 ) get_queryset () : obtain a model from the class properties queryset in queryset data
 2 ) get_object () : from the class attribute queryset in queryset obtained data model, and then the operation target is determined uniquely by the known packet PK
 . 3) get_serializer () : serializer sequence obtained from the class of the class properties serializer_class

 

  • Routing layer

= the urlpatterns [ 
    URL (R & lt ' ^ V2 / Books / $ ' , views.BookGenericAPIView.as_view ()), 
    URL (R & lt ' ^ V2 / Books / (? P <PK>. *) / $ ' , views.BookGenericAPIView. as_view ()), 
] 
# BookGenericAPIView.as_view () => call is APIView of as_view () => View of as_view () => APIView completion of dispatch distribution

 

  • View layer

from rest_framework.generics Import GenericAPIView
 # BookGenericAPIView.as_view () => call is APIView of as_view () => View of as_view () => APIView completion of dispatch distribution 
class BookGenericAPIView (GenericAPIView): 
    QuerySet = models.Book.objects. filter (is_delete = False) 
    serializer_class = serializers.BookModelSerializer 
    lookup_field = ' PK '   # single check is to specify lookup_field = 'pk' attribute 
    # group search: 
    DEF GET (Self, Request, * args, ** kwargs): 
        book_query = Self .get_queryset ()   #Queryset automatically passed to afford the object model class queryset 
        book_ser = self.get_serializer (book_query, MANY = True)   # identical to the sequence of BookModelSerializer 
        book_data = book_ser.data
         return APIResponse (Results = book_data)
     # Shan Zha: 
    DEF GET ( Self, Request, * args, ** kwargs): 
        book_obj = self.get_object ()   # automatically queryset incoming and call lookup_field properties, particularly to obtain a record of the model class (i.e.: Object) 
        book_ser = self.get_serializer (book_obj) 
        book_data = book_ser.data
         return APIResponse (= book_data Results)

 

 

Two .mixins view toolset - assisted GenericAPIView

# 1) There are five tools mixins class files, provided a total of five tools, six utility methods: single investigation, the investigation group, single by single deletion, a single overall change, a single local change 
    - group check ListModelMixin | List ( ) 
     - single check RetrieveModelMixin | Retrieve ()
     - Tenzin CreateModelMixin | the Create ()
     - UpdateModelMixin | Update () single overall change | partial_update () single local change (single delete: change the field)
     - DestroyModelMixin | the destroy () single delete Note: deleted from the database, generally do not
 # 2) inherits tools can simplify the implementation of the request body function, but must inherit GenericAPIView, several class properties and methods required GenericAPIView class provides (see above GenericAPIView class knowledge base) 
    attributes: 
         - QuerySet | Model class object
         -serializer_class | serialization class
         - lookup_field | designated pk 
    method:
         - get_queryset () | get their target
         - get_object () | get specific objects
         - get_serializer () | serialization, deserialization
 # 3) Tools methodological tools category the return value is a response object, if you want to format the formatted data back to the front, a response object tool can get method returns response data by response.data

 

  • Routing layer

urlpatterns = [
    url(r'^v3/books/$', views.BookMixinGenericAPIView.as_view()),
    url(r'^v3/books/(?P<pk>.*)/$', views.BookMixinGenericAPIView.as_view()),
]

 

  • View layer

from rest_framework.mixins Import ListModelMixin, RetrieveModelMixin, CreateModelMixin, UpdateModelMixin
 class BookMixinGenericAPIView (ListModelMixin, RetrieveModelMixin, CreateModelMixin, UpdateModelMixin, GenericAPIView):
     # inherited GenericAPIView purpose: 
    # 1 routing calls as_view GenericAPIView the parent APIView () method 
    # 2. Call the dispatch completer APIView hair 
    # several classes properties and methods provided by the class 3. need GenericAPIView 
    QuerySet = models.Book.objects.filter (is_delete = False) 
    serializer_class = serializers.BookModelSerializer 
    DEF GET (Self, Request, * args, ** kwargs):
         IF  ' PK'  In kwargs:
             # single check: RetrieveModelMixin the retrieve () method is called inside the get_object GenericAPIView () method of 
            the Response = self.retrieve (Request, * args, ** kwargs)
         the else :
             # cluster check: ListModelMixin in list () method is called internal GenericAPIView of get_serializer (queryset, many = True) method 
            response = self.list (Request, * args, ** kwargs)
         # data providing method mixins default response is the response 
        # response.data to get the response data 
        Print (response.data)   # { 'field': 'field value', ...} 
        return APIResponse (Results = response.data) 
    #Monocytogenes: internal create CreateModelMixin in () method is called GenericAPIView of get_serializer (data = request.data) complete sequence of the method, the storage 
    DEF POST (Self, Request, * args, ** kwargs): 
        Response = Self. Create (Request, * args, ** kwargs)
         return APIResponse (Results = response.data) 
    # single overall change: the internal update UpdateModelMixin () method is called the GenericAPIView that get_object () to get the object-specific, so that partial = False reach overall change 
    DEF PUT (Self, Request, * args, ** kwargs): 
        Response = self.update (Request, * args, ** kwargs)
         return APIResponse (Results = response.data)
     #Single locally modified: an internal update UpdateModelMixin in () method is called the GenericAPIView that get_object () to get the object-specific, so that partial = True reaches locally modified 
    DEF Patch (Self, Request, * args, ** kwargs): 
        Response = Self .partial_update (Request, * args, ** kwargs)
         return APIResponse (= response.data Results)

 

Three. Generics  tool view 

1 ) Tools are subclasses of GenericAPIView view, and a different subclass inherits different tools, a rewrite request method
     - ListCreateAPIView: check group, the inside of the package by a single list (), create () Method
     - UpdateAPIView: locally modified single (mono deleted), the entire inner package to change the single update (), partial_update method
 2) If the direct view of the tool function to meet the needs subclassing view tools, and serializer_class to provide queryset

 

  • Routing layer

urlpatterns = [
    url(r'^v4/books/$', views.BookListCreatePIView.as_view()),
    url(r'^v4/books/(?P<pk>.*)/$', views.BookListCreatePIView.as_view()),
]

 

  • View layer

from rest_framework.generics import ListCreateAPIView, UpdateAPIView
class BookListCreatePIView(ListCreateAPIView, UpdateAPIView):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer

 

Four. Viewsets set of views

1 ) are set priority inheritance ViewSetMixin view class, then the class inherits a view (GenericAPIView or APIView)
 #        GenericViewSet, Viewset 
2) ViewSetMixin provides rewritable as_view () method call when as_view view class inherits viewset, configure routing () must pass { request name: function name } dictionary mapping relationship
 #        EG: URL (R & lt '^ V5 / Books / $', views.BookGenericViewSet.as_view ({ 'GET': 'my_get_list'})), 
#        represents get requests to view function processing my_get_list

 

  • Routing layer

the urlpatterns = [
     # View of as_view (): the get request is mapped to the get method of the view class 
    # Viewset of as_view ({ 'get': ' my_get_list'}): the get request is mapped to my_get_list method of the view class of the 
    URL (R & lt ' V5 ^ / Books / $ ' , views.BookGenericViewSet.as_view ({ ' GET ' : ' my_get_list ' })), 
    (R & lt URL ' ?. ^ V5 / Books / (P <PK> *) / $ ' , views. BookGenericViewSet.as_view ({ ' GET ' : ' my_get_obj ' })), 
]

 

  • View layer

from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins
class BookGenericViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
    queryset = models.Book.objects.filter(is_delete=False)
    serializer_class = serializers.BookModelSerializer
    # 群查
    def my_get_list(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)
    # 单查
    def my_get_obj(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

 

GenericAPIView and APIView difference

# Most two views GenericAPIView inherited differences with APIView 
# . 1) GenericViewSet and ViewSet inherit ViewSetMixin, as_view can configure request {:} function mapping relationship 
# 2) GenericViewSet GenericAPIView view class inheritance is used to complete the standard model operator interface class 
# . 3) Viewset APIView view class inheritance is used to complete the model does not need to participate in the class, or model-based user interface nonstandard 
#        post request under standard model-based operation is to add an interface, not landing post meet 
#        post request verification code interface, do not need to participate in the class model 
# case: landing post request, the new data is not complete, but the data submitted by post, the results obtained are not logged in user information, but landing authentication information

V. tool set of views  ModelViewSet

  • View layer

# Has six interfaces: a single investigation, the investigation group, single by single deletion, a single overall change, change a single local 
# Note: The general will certainly rewrite the destroy 
from rest_framework.viewsets Import ModelViewSet
 class BookModelViewSet (ModelViewSet): 
    QuerySet = Models. Book.objects.filter (is_delete = False) 
    serializer_class = serializers.BookModelSerializer 
    # single deletion field 
    DEF the destroy (Self, Request, * args, ** kwargs): 
        instance = self.get_object ()   # get specific model class 
        if  not instance:
             return APIResponse (1, ' delete failed ')
        # 改字段
        instance.is_delete = True
        instance.save()
        return APIResponse(0, '删除成功')
    #
    def get(self, request, *args, **kwargs):
        response = self.list(request, *args, **kwargs)
        return APIResponse(results=response.data)
    # ...

 

  • Routing layer

urlpatterns = [
    url(r'^v6/books/$', views.BookModelViewSet.as_view({'get': 'list', 'post': 'create'})),
    url(r'^v6/books/(?P<pk>.*)/$', views.BookModelViewSet.as_view({'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'})),
]

 

 

Routing components

from django.conf.urls Import the include
 from rest_framework.routers Import SimpleRouter 
Router = SimpleRouter ()
 # all routes and ViewSet view class can be registered, will have '^ v6 / books / $' and '^ v6 / books / (? P <PK> [^ /.] +) / $ ' 
router.register ( ' V6 / Books ' , views.BookModelViewSet) 
the urlpatterns = [
     # a first mode to add a child list 
    URL (R & lt ' ^ ' , the include (Router .urls)), 
] 
# The second way to add a sub-list 
# urlpatterns.extend (router.urls)

 

 

 

 

Guess you like

Origin www.cnblogs.com/waller/p/11707439.html