Django REST Framework: Generics or ModelViewSets?

I use generics and simple URLs for my REST API, but now I run into a problem: I want user actions, simple representations to do some things with my models, for example "run", "publish", etc.

ViewSet provides an action decorator for creating custom actions, but only ViewSets also have power routers, which allows us to simplify everything using railsish convention-over-configuration.

But I find that ModelViewSet gives us the same capabilities as generics: full CRUD, serializers, filters, cusstom pre / post and queryset, so it leads to the question:

Why do generics exist if ModelViewSet gives the same ability and more? What's the difference?

+7
python rest django django-rest-framework
source share
2 answers

The difference is what methods they offer.

For example:

GenericViewSet inherits from GenericAPIView, but does not provide any implementation of the main actions. Only get_object, get_queryset.

ModelViewSet inherits from GenericAPIView and includes implementations for various actions. In other words, you do not need to implement the basic actions in the form of a list, extraction, creation, updating or destruction. Of course, you can override them and implement your own list or your own creation methods.

You can learn more about this in the API REFERENCE section: ModelViewSet

+12
source share

Why do generics exist if ModelViewSet provides the same capabilities and much more?

Let me first rephrase the question a little more explicitly for you ...

"Why are there general concepts when there are also general concepts"

Which actually comes down to the question of why the REST framework supports both views and views. Answer. ViewSets are useful for prototyping or for cases where API URLs are neatly mapped to a fixed congress (e.g. CRUD style APIs). Views are useful for explicit or for cases where your URLs are not fully mapped to fixed congresses.

+3
source share

All Articles