Passing parameters to the view class class sequence
# 1) in the view class instantiation serialized object, context may be provided the content # 2) a partial sequence of the hook class, global hook, create, update process, can be passed over with a view class access self.context Content # Requirements: # 1) in the view class, can be obtained by the login user request.user Request # 2) in the sequence of the class to complete the verify operation and the database data storage, may be required to know the current login user, but the sequence of categories can not access request # . 3) when a serialized object is instantiated, the object passed in the request in the view class
View layer: views.py
class Book(APIView): def post(self, request, *args, **kwargs): book_ser = serializers.BookModelSerializer(data=request_data,context={'request':request}) book_ser.is_valid(raise_exception=True) book_result = book_ser.save() return Response({ 'status': 0, 'msg': 'ok', 'results': serializers.BookModelSerializer(book_result).data })
Layer sequence: serializer.py
class BookModelSerializer(ModelSerializer): class Meta: model = models.Book fields = ('name', 'price') def validate_name(self, value): print(self.context.get('request').method) return value
Second package Response class
""" Response({ 'status': 0, 'msg': 'ok', 'results': [], 'Token': '' # such additional key-value data results },status=http_status,headers=headers,exception=True|False) APIResponse() => Response({'status': 0,'msg': 'ok'}) """
from rest_framework.response import Response class APIResponse (the Response): DEF the __init__ (Self, data_status = 0, data_msg = ' OK ' , Results = None, HTTP_STATUS = None, headers = None, Exception = False, ** kwargs): # initial state of the data: status code status information Data = { ' status ' : data_status, ' MSG ' : data_msg, } # In response to the data volume data # Results may be False, 0 data, the data will be returned in some cases as valid data IF Results IS Not None: data [ ' Results ' ] = Results # additional content data in response to the # IF kwargs None Not IS: # for K, V in kwargs.items (): # setattr (data, K, V) data.update (kwargs) super().__init__(data=data, status=http_status, headers=headers, exception=exception)
View family
""" views: View generics: Tools view mixins: View toolset viewsets: View Sets """ """ learning curve APIView => GenericAPIView => mixins five tools => = generics view of the tool> viewsets of view set """
GenericAPIView base class
# GenericAPIView inherited APIView using fully compatible APIView # Key: GenericAPIView completed on the basis of what things APIView # 1) get_queryset (): queryset data obtained from the model of the class attribute queryset # 2) get_object (): The only operation object data model queryset obtained from the queryset class attribute, then the packet is determined by known pk # 3) get_serializer (): serializer sequence obtained from the class of the class properties serializer_class
urlpatterns = [ url(r'^v2/books/$', views.BookGenericAPIView.as_view()), url(r'^v2/books/(?P<pk>.*)/$', views.BookGenericAPIView.as_view()), ]
from rest_framework.generics import GenericAPIView class BookGenericAPIView(GenericAPIView): queryset = models.Book.objects.filter(is_delete=False) serializer_class = serializers.BookModelSerializer # Custom primary key known group name lookup_field = ' PK ' # cluster take # DEF GET (Self, Request, * args, ** kwargs): # book_query self.get_queryset = () # book_ser = self.get_serializer (book_query, MANY True =) # book_data = book_ser.data # return APIResponse (Results = book_data) # 单取 def get(self, request, *args, **kwargs): book_query = self.get_object() book_ser = self.get_serializer(book_query) book_data = book_ser.data return APIResponse(results=book_data)
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 partial change # 2) tools can inherit request functions to achieve simplification body, but must inherit GenericAPIView, several class attributes and methods (see above GenericAPIView knowledge base class) needs to provide GenericAPIView class # 3) tools tools method return value is a Response object, if you want to format formatted data back to the front, a response object tool can get method returns response data by response.data
urlpatterns = [ url(r'^v3/books/$', views.BookMixinGenericAPIView.as_view()), url(r'^v3/books/(?P<pk>.*)/$', views.BookMixinGenericAPIView.as_view()), ]
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin class BookMixinGenericAPIView(ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, GenericAPIView): queryset = models.Book.objects.filter(is_delete=False) serializer_class = serializers.BookModelSerializer def get(self, request, *args, **kwargs): if 'pk' in kwargs: Response = self.retrieve (Request, * args, ** kwargs) the else : # response object list is provided a method mixins Response, like the object formatted APIResponse Response = self.list (Request, args *, ** kwargs) # Response response.data data are stored in the return APIResponse (Results = response.data) def post(self, request, *args, **kwargs): response = self.create(request, *args, **kwargs) return APIResponse(results=response.data) def put(self, request, *args, **kwargs): response = self.update(request, *args, **kwargs) return APIResponse(results=response.data) def patch(self, request, *args, **kwargs): response = self.partial_update(request, *args, **kwargs) return APIResponse(results=response.data)
Tool Views
# 1) tool views are subclasses GenericAPIView, and the different sub-class inherits the tools do not listen, and rewrite the request method # 2) If the direct view function tool to meet the demand, only need to inherit tool view offers queryset and can serializer_class
urlpatterns = [ url(r'^v4/books/$', views.BookListCreatePIView.as_view()), url(r'^v4/books/(?P<pk>.*)/$', views.BookListCreatePIView.as_view()), ]
from rest_framework.generics import ListCreateAPIView, UpdateAPIView class BookListCreatePIView(ListCreateAPIView, UpdateAPIView): queryset = models.Book.objects.filter(is_delete=False) serializer_class = serializers.BookModelSerializer
View Set
# 1) is set priority inheritance ViewSetMixin view class, then the class inherits a view (GenericAPIView or APIView) # GenericViewSet, Viewset # when 2) ViewSetMixin provides as_view rewritable () method of the view class inheritance viewset, configure routing call as_view () must pass request name - the 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
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 ' } )), url(r'^v5/books/(?P<pk>.*)/$', views.BookGenericViewSet.as_view({'get': 'my_get_obj'})), ]
from rest_framework.viewsets import GenericViewSet from rest_framework import mixins class BookGenericViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, 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)
# . 1) and GenericViewSet Viewset inherit ViewSetMixin, as_view can configure request - the function mapping # 2) GenericViewSet GenericAPIView view class inheritance is used to complete the standard model-based user interface # . 3) Viewset inherited APIView view class, used to complete the model class need not participate in, or non-standard model-based user interface # post request under standard model-based operation is to add an interface, does not satisfy the landing post # post interface to request a verification code, does not require the model class participate # authentication information login 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: case
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'})), ]
from rest_framework.viewsets import ModelViewSet class BookModelViewSet(ModelViewSet): queryset = models.Book.objects.filter(is_delete=False) serializer_class = serializers.BookModelSerializer # Delete is not a database, but remove fields in the record DEF the destroy (Self, Request, * args, ** kwargs): instance = self.get_object () # of the type: models.Book IF not instance: return APIResponse (1, ' Delete failed ' ) # actual operation, before it made a judgment instance.is_delete = True instance.save() return APIResponse (0, ' deleted successfully ' )
from django.conf.urls import include from rest_framework.routers import SimpleRouter Router = SimpleRouter () # all routes with ViewSet view class can be registered, generate '^ 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)