Django REST Framework: Generics or ModelViewSets?

2019-04-06 01:48发布

问题:

I use generics and plain urls for my REST API, but now I stuck with problem: I want custom actions, simple views to make some things with my models, like "run", "publish", etc.

ViewSet gives action decorator to create custom actions, but only in ViewSets, also, there is stepial routers, which gives us ability to simplify everything using railsish convention-over-configuration.

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

Why there is generics if ModelViewSet gives same abilities and more? What a difference?

回答1:

The difference is what methods they offer.

For example:

GenericViewSet inherits from GenericAPIView but does not provide any implementations of basic actions. Just only get_object, get_queryset.

ModelViewSet inherits from GenericAPIView and includes implementations for various actions. In other words you dont need implement basic actions as list, retrieve, create, update or destroy. Of course you can override them and implement your own list or your own create methods.

You can read more about it, in the API REFERENCE section: ModelViewSet



回答2:

Why there is generics if ModelViewSet gives same abilities and more?

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

"Why are there Generic Views, when there are also Generic ViewSets"

Which really just comes down to a question of why REST framework supports both views and viewsets. Answer - ViewSets are useful for prototyping or for cases when your API URLs neatly map to a fixed convention throughout (eg CRUD style APIs). Views are useful for being explicit, or for cases when your URLs do not neatly map to a fixed convention throughout.