Generic Views vs APIView vs Viewsets, vs ModelViewsets

Viewed 1963

I just started learning Django Rest Framework and I get to now about 4 concepts APIView, Viewsets, Modelviewsets, GenericView. What is the difference between them and which of them is more efficient to use in the development of rest APIs and why?

1 Answers

There is no standard but you can start with this simple strategy:

  1. Several actions in one class and basic CRUD ---> Viewset (ModelViewSet and ReadOnlyModelViewSet are most useful)

  2. Specific action on a model class ---> Generic Views (RetrieveModelMixin, ListAPIView, UpdateModelMixin, DestroyModelMixin, CreateModelMixin)

  3. If you want to write all create, update, ... methods yourself you can use APIView and write them in your get, post, put, ... methods (Difference between APIView & GenericAPIView is only you cant use some builtin methods in your class , like queryset, serializer_class, ... )

  4. And if you want to write everything from scratch you can write your apis in function base

  • Most of the times you have to write you apis with Generic Views & If you learn all of the Generic APIView best practices, it has so much power and your will be so clean, readable and scalable
  • Buy if you have simple Models you can use Viewset

I use GenericAPIView in normal APIs & use APIView in the custom ones (like most of APIs in Admin Panel)

Related