Django REST Framework allows us to combine the logic for a set of related views in a single view class. They are called Viewsets. ViewSets work exactly same as Generic Views. The only difference is using ViewSet we don’t have to create separate views for getting list of objects and detail of one object. We do not need to configure the urls with ViewSets. Routers generates urls automatically and binds methods for different request method types of ViewSet.
Why we should use ViewSets & Routers.
In larger projects multiple endpoints (URLs) can be difficult to maintain . Besides, same lines of code are repeated in the views. These problems can be solved using ViewSets & Routers.
Advantages of using ViewSet.
- Can speed up API development
- Additional layer of abstraction
- A single viewset can replace multiple views
- Repeated logic can be combined into a single class
- Combined logic for a set of related views in a single class
- Write less code – Promotes DRY (Don’t Repeat Yourself)
Firstly, we will see usage of Viewset class and then ModelViewset class.