Article

ViewSets in Django Rest Framework

Last updated 
Apr 13, 2019
 min read

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.

Function-based Views

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})

Class-based Views

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.

Implementing ViewSets

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

Using DefaultRouter for Routing

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

Authors

Naitik Shah

Software Engineer
I’m a Software Engineer with a strong focus on delivering high-quality, scalable applications. I specialize in AWS and enjoy tackling challenging problems to create seamless, user-friendly experiences. Constantly learning and adapting, I’m driven by a passion for building impactful software that makes a difference.

Tags

No items found.

Have a project in mind?

Read