DRF view set

  • The class view inherits from the viewset, and the corresponding processing methods have been encapsulated in the viewset
class StudentInfoViewSet(viewsets.ViewSet):

    def list(self, request):

    def retrieve(self, request, pk=None):
  • The ViewSet view set class no longer implements methods such as get(),post(), but implements actions:
list() provides a set of data
 retrieve() provides a single data
 create() create data
 update() to save the data
 Destroy() delete data
  • When setting the route, you need to map the request mode and action organization: in as view

Note: if the action is to add, delete, update and retrieve a single object, you need to pass in the 'PK' value in the path

urlpatterns = [
    url(r'^students/$', StudentInfoViewSet.as_view({'get':'list'}),
    url(r'^students/(?P<pk>\d+)/$', StudentInfoViewSet.as_view({'get': 'retrieve'}) # Need to add keyword parameters to the path

action property in ViewSet

  • In the view set, when the action object attribute is stored, the Request object is mapped from Request method - > Request action
  • When overriding some methods within the view set, different business processes can be performed according to different actions
  • Demo
def get_serializer_class(self): # Overriding method to get serializer object
    if self.action == 'create': # If the requested action is create(post request), xxx logic
        return OrderCommitSerializer
        return OrderDataSerializer

Custom actions in ViewSet

  • Custom actions use the rest framework.decorators.action decorator
  • The user-defined action name is the same as the method name. For example, when the user-defined method name is' test1 ', the action name corresponding to the changed method name is' test1'
  • The decorator receives two parameters:
  • methods: the request method supported by this action, list passing
  • detail: indicates whether the object to be processed in the action is the object of the view resource (that is, whether to obtain the primary key through the url path):
  • True indicates the data object corresponding to the primary key obtained through the URL
  • False means not to use URL to get primary key


	# Modification of student information
    @action(methods=['put'], detail=True)
    def info(self, request, pk):
        # # Get a database object according to pk
        # instance = super().get_object()
        # # Only a simple serializer is needed to modify info
        # self.serializer_class = student_info_serializer
        # info_valid = super().get_serializer(instance,data=request.data)
        # info_valid.is_valid(raise_exception=True)
        # info_valid.save()
        # return Response(info_valid.data)

		# Another way
        self.serializer_class = student_info_serializer
        instance = self.get_object() # Get a serializer object based on pk
        order_valid = self.get_serializer(instance, request.data) # Get a serializer object according to database u item
        order_valid.is_valid() # data verification
        order_valid.save() # Data preservation
        return Response(order_valid.data) # Return front end

Common view set parent class

  • ViewSet
  • Inherited from APIView, it has the same function as APIView, providing identity authentication, permission verification, traffic management, etc
  • There is no action method provided in the ViewSet. We need to implement the action method ourselves
  • GenericViewSet
  • Inherited from GenericAPIVIew, it also functions like genericapiew. It provides methods such as get object and get queryset to facilitate the development of list view and detail information view
  • ModelViewSet
  • Inherited from genericapiiew, including ListModelMixin, RetrieveModelMixin, CreateModelMixin, UpdateModelMixin, DestoryModelMixin
  • ReadOnlyModelViewSet
  • Inherited from genericapiiew, including ListModelMixin,RetrieveModelMixin

View set class inheritance relationship

Published 17 original articles, won praise and visited 33
Private letter follow

Tags: Database Attribute REST

Posted on Thu, 12 Mar 2020 08:47:32 -0400 by vigge89