Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ViewSet, ModelViewSet and APIView

What are the advantages of ViewSet, ModelViewSet and APIView. In the django-rest-framework documents it is not clear, it does not say when to use ViewSet, ModelViewSet and APIView. I want to implement an API that will have a business logic in there, a great business logic with data processing as well, what should be used for this case? I researched a lot and managed to understand a little about routers and urlpatterns but I didn't understand which one about views.

like image 843
Dedadino Avatar asked Jan 01 '23 07:01

Dedadino


1 Answers

Summarizing: on one hand you have the APIView, which is the most generic of the three, but also in which you must do almost all business logic 'manually'. You have the class methods mapping http methods (get, post, ...) plus some class attributes to configure things like authentication, rendering, etc.

Often you'll be developing endpoints to interact with resources (entities, like Users, Products, Orders, etc.) via CRUD operations, and that is what ViewSet is for: they have more semantic class methods like list, create, retrieve ... that the router can then automatically map to urls and http methods at the expense of making some assumptions: for example, the retrieve assumes the http call to be GET /you_resource/<pk>. It is more rigid than a generic APIView but it takes away from you some boilerplate/manual config that you would have to repeat again and again in most cases.

One step further is the ModelViewSet, which is an extension of the ViewSet for when you are working with Django models. Just specifying a serializer_class and a queryset you have all the CRUD operations of the ViewSet ready to go. Obviously, you can also add your own methods to a ViewSet or customize the behavior of its default methods.

In my experience, it pays off to use ViewSets. The code looks cleaner and you avoid some boilerplate code. The assumptions it makes are reasonable, and I would even say that you probably will end up with a cleaner API design following them.

like image 88
gmc Avatar answered Jan 02 '23 21:01

gmc