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

Viewed 366

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?

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.

Related