ViewSets in Django Rest Framework

Naitik Shah
Aubergine Solutions
2 min readApr 5, 2019

As we all know there are 2 types of Views in Django

I will take a quick example to show how the code looks in both the 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 much of the code.

  • Function-based Views
@login_required
@csrf_exempt
def product_list(request):
if request.method = "GET":
products = Product.objects.all()
filtered_products = ProductFilter(request.GET, queryset=products)
serializer = ProductSerializer(filtered_products.qs, many=True)
return Response({"data": serializer.data, "status": status.HTTP_200_OK})
elif request.method = "POST":
data = JSONParser().parse(request)
serializer = ProductSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response({"data":serializer.data, "status": status.HTTP_201_CREATED})
return Response({"data": serializer.data, "status": status.HTTP_400_BAD_REQUEST})
  • Class-based Views
class ListProducts(ListCreateAPIView):
permission_classes = (IsAuthenticated,)
serializer_class = ProductSerializer
filter_class = ProductFilter
queryset = Product.objects.all()

class ProductDetails(RetrieveUpdateDestroyAPIView):
permission_classes = (IsAuthenticated,)
serializer_class = ProductSerializer
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.

from rest_framework import viewsets

class ProductViewSet(mixins.CreateModelMixin,
mixins.ListModelMixin,
mixins.UpdateModelMixin,
mixins.RetrieveModelMixin,
mixins.DestropModelMixin,
viewsets.GenericViewSet):
permission_classes = (IsAuthenticated, )
serializer_class = ProductSerializer
queryset = Product.objects.all()
filter_class = ProductFilter

Now ViewSets bring the concept of a route, we will use DefaultRouter function to instantiate.

from rest_framework.routers import DefaultRouter
router = DefaultRouter()
# The default routers included with REST framework will
# provide routes for a standard set of # create/retrieve/update/destroy style actions

router.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 know DRF link:
https://www.django-rest-framework.org/api-guide/viewsets/#viewsets

That's it! enjoy!

Your clap for my article means a lot :P!

--

--