Django-Rest-Framework(DRF) supports three different types of views. They are
Based on the developer convenience developer can choose the type of view.
Examples: create 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 Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
@api_view(['POST'])
# other decorators if required
@permission_classes([IsAuthenticated])
def user_create(request):
serializer = UserSerializer(data=request.POST)
if serializer.is_valid():
password = serializer.validated_data.get("password")
serializer.object.set_password(password)
serializer.save()
return Response({"message": "User Created"}, status=status.HTTP_201_CREATED)
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.permissions 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, include
from rest_framework import routers
from . import viewsets
router = routers.DefaultRouter()
router.register(r'users', viewsets.UserViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
If you observe the above example code you can absorve that we have to write complete code inorder to get the full functionality even if it is a common case. But where as in generic views we can avoid the writing of repetitive code for common cases. In both the generic views and function based views we configured the urls with views. But, In viewsets we registered the ViewSet class with register. The advantage of register is that it can generate the urls & binds the appropriate methods to different request method types. If you are dealing with large project more number of views and url configurations. It will make maintenace of project difficult. By using Routers and ViewSets we can better maintain the project though it deals with a little abstraction.