ViewSets in Django Rest Framework

As we all know there are 2 types of Views in Django
I will give a quick example to show how the code looks in both views. I know many of you know this and you can surely skip the below code if you want, but I mainly want to show how ViewSets can help in reducing a lot of the code.
1@login_required
2@csrf_exempt
3def product_list(request):
4 if request.method = "GET":
5 products = Product.objects.all()
6 filtered_products = ProductFilter(request.GET, queryset=products)
7 serializer = ProductSerializer(filtered_products.qs, many=True)
8 return Response({"data": serializer.data, "status": status.HTTP_200_OK})
9 elif request.method = "POST":
10 data = JSONParser().parse(request)
11 serializer = ProductSerializer(data=data)
12 if serializer.is_valid():
13 serializer.save()
14 return Response({"data":serializer.data, "status": status.HTTP_201_CREATED})
15 return Response({"data": serializer.data, "status": status.HTTP_400_BAD_REQUEST})
1class ListProducts(ListCreateAPIView):
2 permission_classes = (IsAuthenticated,)
3 serializer_class = ProductSerializer
4 filter_class = ProductFilter
5 queryset = Product.objects.all()
6
7class ProductDetails(RetrieveUpdateDestroyAPIView):
8 permission_classes = (IsAuthenticated,)
9 serializer_class = ProductSerializer
10 queryset = Product.objects.all()
As you can observe, things are getting more and more crisp in the form of code.
If we talk about urls.py, the main difference comes when you have to specify Class-based Views with as_view() callable function to define them as a View for urls which is not the case with Function-based Views.
Let us now consider the above example for ViewSets.
1from rest_framework import viewsets
2
3class ProductViewSet(mixins.CreateModelMixin,
4 mixins.ListModelMixin,
5 mixins.UpdateModelMixin,
6 mixins.RetrieveModelMixin,
7 mixins.DestropModelMixin,
8 viewsets.GenericViewSet):
9 permission_classes = (IsAuthenticated, )
10 serializer_class = ProductSerializer
11 queryset = Product.objects.all()
12 filter_class = ProductFilter
Now ViewSets brings the concept of a route, we will use DefaultRouter function to instantiate.
1rom rest_framework.routers import DefaultRouter
2router = DefaultRouter()
3# The default routers included with REST framework will
4# provide routes for a standard set of
5# create/retrieve/update/destroy style actions
6
7router.register('products', ProductViewSet)
Now you can access all the CRUD actions using this single view, and of course, you can override these actions if you want the action to perform any extra data processing.
For more reference to ViewSets, you can check the well-known DRF link:
That's it! Enjoy!
Also Read: Implementing Two-Factor Authentication in Django Admin Panel