Working with class-based views

We will write our RESTful Web Service by coding class-based views. We will take advantage of a set of generic views that we can use as our base classes for our class-based views to reduce the required code to the minimum and reuse the behavior that has been generalized in the Django REST framework.

We will create subclasses of the two following generic class views declared in the rest_framework.generics module:

  • ListCreateAPIView: This class view implements the get method that retrieves a listing of a queryset and the post method that creates a model instance
  • RetrieveUpdateDestroyAPIView: This class view implements the get, delete, put, and patch methods to retrieve, delete, completely update, or partially update a model instance

Those two generic views are composed by combining reusable bits of behavior in the Django REST framework implemented as mixin classes declared in the rest_framework.mixins module. We can create a class that uses multiple inheritance and combine the features provided by many of these mixin classes.

The following line shows the declaration of the ListCreateAPIView class as the composition of ListModelMixin, CreateModelMixin, and rest_framework.generics.GenericAPIView:

class ListCreateAPIView(mixins.ListModelMixin, 
                        mixins.CreateModelMixin, 
                        GenericAPIView): 

The following line shows the declaration of the RetrieveUpdateDestroyAPIView class as the composition of RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin, and rest_framework.generics.GenericAPIView:

class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin, 
                                   mixins.UpdateModelMixin, 
                                   mixins.DestroyModelMixin, 
                                   GenericAPIView): 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.237.79