Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I choose the type of view in Django Rest Framework

I can create my view in Django with :

  • Function Base View
  • Class Base View
  • Generic Views & Mixins
  • ViewSets

Now is there any standard to tell us when should we use which?

and why we have this much type at all?

like image 578
Ali Rn Avatar asked Sep 13 '25 03:09

Ali Rn


1 Answers

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

  1. Specific action on a model class -- generic views (RetrieveAPIView, ListAPIView, UpdateAPIView, etc.)
  2. Several actions in one class and basic CRUD -- ViewSets (ModelViewSet and ReadOnlyModelViewSet are most useful)
  3. Some action on 1 instance -- ViewSet + @action(detail=True)
  4. Some action on several or all objects -- ViewSet +@action(detail=False)
  5. Simplest custom actions -- function based views or @action again.

Also check DRF views classes for quick overview.

like image 87
Mark Mishyn Avatar answered Sep 15 '25 16:09

Mark Mishyn