Generic, practical based and class based views in Django REST Structure

Spread the love

Django-Rest-Framework( DRF) supports 3 different kinds of views. They are

  1. Function Based Views
  2. Class Based Views/ Generic Views
  3. ViewSets

Based on the developer convenience developer can choose the type of view.

Function based views( FBV):

  • Our view must return the action as per the requirements of the django rest structure ( Response however not reggular HttpResponse).
  • Django REST supplies a set of designers that will examine whether the view returning the right Response or not.
  • Django REST provides the following designers
  • api_view, renderer_classes, parser_classes, authentication_classes,
  • throttle_classes, permission_classes, detail_route, list_route
  • @api_view: It converts the function based view into a subclass of API view.
  • @renderer_classes: It takes an iterable set of renderer classes which helps in producing response to a demand with various media types.
  • @parser_classes: It takes an iterable set of parser classes which permits REST to accept demands with different numerous media types.
  • @authentication_classes: It takes an iterable set of authentication classes that will permit REST validate the request.
  • @throttle_classes: It takes an iterable set of throttle classes that will restrict variety of demands per user in a specific amount of time.
  • @permission_classes: It takes an iterable set of permission classes that enables REST to check whether user enabled to take the asked for resource or not.
  • @detail_route: It will mark the function/method to be served for detail demand.
  • @list_route: It will mark the function/method to served for list request.
  • All other designers must come after @api_view
  • Every decorator takes a single argument which needs to be a list or tuple of classes other than @detail_route, @list_route
  • We require to configure the urls for FBV views.

Generic Views( Class Based Views – CBV):

  • REST class based views are similar to django class based views.
  • Every inbound demand will be dispatched to the proper approach handler just like django CBV.
  • APIView is the base class for all the DRF CBV and GenericAPIView is the base class for all the generic CBV.
  • Following are the generic views offered by the DRF
  • CreateAPIView, ListAPIView, RetrieveAPIView, DestroyAPIView, UpdateAPIView, ListCreateAPIView,
  • RetrieveUpdateAPIView, RetrieveDestroyAPIView, RetrieveUpdateDestroyAPIView
  • CreateAPIView:
    • Acquire this class only if you wish to develop a design circumstances.
    • Just like CreateView in django.
    • Just enables the demand type “POST”.
  • ListAPIView:
    • Inherit this class just if you want to recover list of model instances.
    • It works just like ListView in django.
    • You can override the technique “ get_queryset” if you want conditional queryset to be returned.
    • It only permits the request type “GET”
  • RetrieveAPIView:
    • Acquire this class just if you wish to obtain information of a specific design instance.
    • You need to offer a distinct identifier as a argument in the url.
    • It works much like DetailView in django.
    • It only permits the demand type “GET”
  • DestroyAPIView:
    • Inherit this class only if you wish to erase a model circumstances.
    • You have to offer a distinct identifier as a argument in the url.
    • It just permits the demand type “ERASE”
  • UpdateAPIView:
    • Inherit this class just if you wish to update a design instance.
    • You need to provide a distinct identifier as a argument in the url.
    • Use request type “PUT” for complete update of model instance.
    • Usage request type “PATCH” for partial update.
    • It just allows the request types “PUT”, “SPOT”
  • ListCreateAPIView:
    • Acquire this class if you wish to produce a list of model instances at once.
    • It just permits the request types “GET”, “POST”
    • Usage demand type “POST” for developing the list of design circumstances.
    • Use demand type “GET” for retrieving the list of model circumstances.
  • RetrieveUpdateAPIView:
    • Inherit this class if you want both performances retriving and updating the model circumstances.
    • It allows request type “GET”, “PUT”, “PATCH”
  • RetrieveDestroyAPIView:
    • Acquire this class if you desire both performances retriving and erasing the design instance.
    • It permits demand type “GET”, “DELETE”
  • RetrieveUpdateDestroyAPIView:
    • Inherit this class if you want the 3 performances retrive, upgrade, delete for the exact same url.
    • It enables request type “GET”, “DELETE”, ” PUT” and “SPOT”
  • Acquire the above mentioned classes based on your requirement.
  • Unlike in FBV we do not utilize decorators instead we use class attributes for rendereres, authorizations, parsers, throttles, and so on
  • To customise default behaviour of the DRF by overriding the appropriate methods and characteristics.
  • We require to configure the urls for CBV views.
  • To utilize CBV we need to have standard understanding of Item Oriented Programming.

ViewSets:

  • ViewSets works precisely same as generic views( CBV). The only distinction is that it allows us to integrate the reasoning for set of associated views in a single class
  • It does not offer approach handlers like “get”, “post”, “put”, and so on
  • We do not configure the urls with ViewSets instead we utilize Routers to sign up viewsets.
  • Routers creates urls for ViewSets instantly and binds techniques like ” obtain”, “list”, “develop”, “upgrade”, “delete”, “partial_upate” for various request method types( GET, POST, etc).
  • DRF provides 3 generic viewsets GenericViewSet, ReadOnlyModelViewSet, ModelViewSet.
  • GenericViewSet:
    • It does not include the basic actions/methods like “list”, “create”, and so on we need to specify these methods in order to utilize it.
    • But It offers methods like ” get_object” and ” get_queryset”
    • Acquire it and utilize it only if you want to carry out completly brand-new behaviour instead of the fundamental behaviour supplied by DRF.
  • ReadOnlyModelViewSet:
    • It provides the performance of CBV views ListAPIView and RetrieveAPIView in a single class.
    • It accepts just accepts the demand technique type ” GET”
  • ModelViewSet:
    • It supplies total functionality of CBV of DRF in a single class.
    • You can avoid writing of 6 various classes.
    • You can likewise prevent configuring of urls for classes.

Examples: develop user with django-rest-framework

# serializers.py.
from django.contrib.auth.models import User.
from rest_framework import serializers.

class UserSerializer( serializers.ModelSerializer):.
class Meta:.
model = User.
fields = (" first_name", "last_name", "email").

# function based views.py.
from django.contrib.auth.models import User.
from.serializers import UserSerializer.
from rest_framework. decorators import api_view, permission_classes.
from rest_framework. response import Reaction.
from rest_framework import status.
from rest_framework. consents import IsAuthenticated.

@api_view(['POST']).
# other decorators if required.
@permission_classes([IsAuthenticated]).
def user_create( demand):.
serializer = UserSerializer( data= request.POST).
if serializer.is _ legitimate():.
password = serializer.validated _ data.get(" password").
serializer.object.set _ password( password).
serializer.save().
return Response( "message": "User Produced", status= status.HTTP _201 _ DEVELOPED).
else:.
return Response( serializer.errors).

# function based urls.py.
from django.conf.urls import url.
from. import views.

urlpatterns =[
   url(r'^user-create/$',  views.user_create, name="user-create"),
]

# generic views.py.
from rest_framework import generics.
from rest_framework. approvals import IsAuthenticated.
from.serializers import UserSerializer.

class UserCreateView( generics.CreateAPIView):.
serializer_class = UserSerializer.
permission_classes = (IsAuthenticated, ).

# generic urls.py.
from django.conf.urls import url.
from. import views.
urlpatterns =[
   url(r'^user-create/$',  views.UserCreateView.as_view(),  name="user-create"),
]
# viewsets.py.
from rest_framework import viewsets.

class UserViewSet( viewsets.ModelViewSet):.
serializer_class = UserSerializer.
permission_classes = (IsAuthenticated, ).

# viewsets urls.py.
from django.conf.urls import url, consist of.
from rest_framework import routers.
from. import viewsets.

router = routers.DefaultRouter().
router.register( r' users', viewsets.UserViewSet).

urlpatterns = [
    url(r'^', include(router.urls)),
]

In both the generic views and function based views we configured the urls with views. In viewsets we signed up the ViewSet class with register. If you are dealing with big task more number of views and url setups.

References:


http://www.django-rest-framework.org/

https://github.com/encode/django-rest-framework/tree/master/rest_framework

Read More