Simplifying the code using ViewSets
We have seen how we can optimize our code and make it more concise using class-based generic views. ViewSets and routers help us further simplify our code. As the name indicates, ViewSets are a set of views represented in a single class. For example, we used the AllBooks
view to return a list of all books in the application and the BookDetail
view to return the details of a single book. Using ViewSets, we could combine both these classes into a single class.
DRF also provides a class named ModelViewSet
. This class not only combines the two views mentioned in the preceding discussion (list
and detail
) but also allows you to create, update, and delete model instances. The code needed to implement all this functionality could be as simple as specifying the serializer and queryset
. For example, a view that allows you to manage all these actions for your user model could be defined as tersely as the following:
class UserViewSet(viewsets.ModelViewSet...