Viewset vs APIView
The differences between APIView and Viewset vary depending on the particular needs and requirements. Therefore, we can provide a code-based example to decide which method should be used:
Now let’s do the same operations using Viewset:
class BlogPostViewSet(viewsets.ModelViewSet):
queryset = BlogPost.objects.all()
serializer_class = BlogPostSerializer
At this point, we wrote less code using Viewset compared to the previous example created with APIView. Viewset contains several predefined methods that can be used for multiple operations, making model operations easier. Also, for customized operations, Viewset can be easily extended with extra methods provided by the Django Rest Framework.
In addition, routers combined with Viewset can automatically match URLs and associate them with the view class, allowing us to easily perform URL routing. This is especially useful in large-scale projects or projects that work with many models.
router = routers.DefaultRouter()
router.register(r'blog-posts', BlogPostViewSet)
urlpatterns = [
path('', include(router.urls)),
]
In this example, the router element registers our Viewset class and automatically generates the URLs required for the predefined CRUD operations. Thus, you can perform basic CRUD operations by sending GET, POST, PUT, PATCH and DELETE requests to the URL “/blog-posts/”.
Conclusion
APIView
is derived from Django’s base View class, whileViewset
is derived from a specialViewSet class
of the Django Rest Framework.
Reference
- Django APIView vs Viewsets Which one to Choose?
- APIView vs Viewsets
- Views vs Generic Views vs ViewSets
- GenericAPIView and Mixins
- More views and viewsets: offical docs
- Generic, Functional Based and Class Based Views in Django REST Framework
-
Viewsets vs Generic Views vs APIView vs Function Based Views: reddit
- Comprehensive guide to GenericAPIViews in Django REST Framework
- Django REST Framework: Generics or ModelViewSets?: stackoverflow