Twelfth cell base view


GenericAPIView inherits from APIVIew and adds general support methods that may be used for list view and detail view. Generally, it can be combined with one or more Mixin extension classes to realize other more advanced functions. In summary, GenericAPIView is the base class related to data management and will learn about method operation in the future

from rest_framework.generics import GenericAPIView

GenericAPIView internal properties

 Query result object to be operated in list view
 The serializer used in the view is generally aimed at the previous one queryset Specified

List view individual properties

pagination_class: Paging control class for paging settings
filter_backends: The back-end of filtering control can filter the data in fields

Detail page view individual properties

lookup_url_kwarg: Parameter naming for dynamic routing
lookup_field: Filtered***orm***parameter

General method of list and detail view

get_queryset(self): The query set used by the return view is the basis and default return for obtaining data in list view and detail view queryset Property, support override
get_serializer_class(self): Returns the serializer class, which is returned by default serializer_class´╝îCan be rewritten
get_serializer(self, args, `**kwargs`): Returns the serializer object

Detail page view separate method


  • Return the model class data object required by the detail view. Lookup is used by default_ Field parameter to filter queryset. A model class object that can be called to get detailed information in an attempt
  • If the model class object accessed in detail does not exist, 404 will be returned. If multiple duplicates are accessed, an error will also be reported. By default, the get method is used for orm query
  • This method will use the check provided by APIView by default_ object_ The permissions method checks whether the current object has permission to be accessed

Function division of mixed classes

GenericAPIView only provides data, but the corresponding access function is not implemented. Therefore, DRF also has five mixed classes that provide methods, which can complete the basic addition, deletion, modification and query functions. We also call Mixin mixed class. Through the multi inheritance between GenericAPIView and mixed class, more complex interface functions can be realized. GenericAPIView provides data, while mixed class provides operations

  • The list view extension class provides * * * list(request, *args, **kwargs) * * * methods to quickly implement the list view

  • Return 200 status code by default

  • The list method of Mixin will filter and page the data

  • Create a view extension class and provide * * * create(request, *args, **kwargs) * * * method to quickly create the view of resources

  • 201 status code is returned successfully.

  • If the serializer fails to verify the data sent by the front end, a 400 error is returned

  • The details view extension class provides * * * retrieve(request, *args, **kwargs) * * * methods to return individual data

  • If the detail data exists, return 200, otherwise return 404

  • Update the view extension class and provide * * * update(request, *args, **kwargs) * * * methods

  • Provide * * * partial at the same time_ Update (request, * args, * * kwargs) * * * method can realize local update.

  • 200 is returned successfully, and 400 error is returned when the serializer fails to verify the data


Delete the view extension class and provide * * * destroy(request, *args, **kwargs) * * * methods

You can quickly delete an existing data object

204 is returned for success, 404 is returned for nonexistence

Combination of mixed class and GenericAPIView

class ListView(ListModelMixin, GenericAPIView):
    queryset = Model.objects.all()
    serializer_class = Ser
    def get(self, request):
        return self.list(request)
class CreateSer(serializers.ModelSerializer):
    class Meta:
        model = model
        fields = '__all__'
class CreateView(GenericAPIView, CreateModelMixin):
    serializer_class = CreateSer
    def post(self, request):
        return self.create(request)

With lookup_field is the filtering field of orm, and the lookup is queried_ url_ For a piece of data details of the corresponding value of kwarg, the queryset parameter needs to be provided as the location of the query

class DetailView(GenericAPIView, RetrieveModelMixin):
    queryset = model.objects.all()
    serializer_class = DetailSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'
    def get(self, request, pk):
        return self.retrieve(request)
  • The routes set and accessed are as follows:
path('detailview/<int:pk>/', DetailView.as_view()),

Lookup is also required to implement the update_ Field and lookup_url_kwarg is used to determine the updated data, and the data can be submitted by means of put/post. Compare the created mixed classes

class UpdateView(GenericAPIView, UpdateModelMixin):
    queryset = model.objects.all()
    serializer_class = UpdateSer
    lookup_field = 'pk'  # Updated data filter field
    lookup_url_kwarg = 'pk'  # Parameter value of updated data filtering condition
    def put(self, request, pk):
        return self.update(request)

When the data in the requested light transmission does not need to be updated

# put
    "age": ...

Note: if you need to update the serializer field locally, but not all data will be updated, you can pass the partial parameter as True at the update parameter position


For example, deleting an existing data, like updating, requires data filtering conditions. If it is not transmitted, it is queried by using the fixed pk mechanism

class DeleteView(GenericAPIView, DestroyModelMixin):
    queryset = model.objects.all()
    def delete(self, request, pk):
        return self.destroy(request)

13.3 application of extension class

# Simplify code with extension classes
class TeachersView(ListCreateAPIView):
    queryset = Teacher.objects.all()
    serializer_class = TeacherSerializer

class TeacherView(RetrieveUpdateDestroyAPIView):
    queryset = Teacher.objects.all()
    serializer_class = TeacherSerializer
    lookup_field = "id"
    lookup_url_kwarg = "id"

class StudentsView(ListCreateAPIView):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer

class StudentView(RetrieveUpdateDestroyAPIView):
 	# 1. Specify query result set
    queryset = Student.objects.all()
    # 2. Specify serializer
    serializer_class = StudentSerializer
     # 3. Specify dynamic parameters
    lookup_url_kwarg = "id"
    # 4. Specify the filtered ORM field
    lookup_field = "id"

class StudentView3(ListAPIView):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer2

Tags: Python programming language

Posted by daz1034 on Fri, 13 May 2022 01:05:54 +0300