Search code examples
django-rest-frameworkdjango-rest-viewsets

What is the difference between method handlers such .get, .post and actions such as .list, .create


I am learning Django Rest Framework and one of the things I have noticed is that Viewsets provide actions such as .list, .post instead of method handlers such as .get, .post which in turn are provided by Views. The documentation says that actions are more flexible than method handlers but I can't seem to find any reason for this. Could you please share some information on why does Viewsets use actions and not the method handlers?​


Solution

  • request handlers like .get() and .post() are based on http request methods, while actions like .create() or .list() are from a functionality point of view. Suppose you have a view class that can return a single user's info by user id or return all users in sorted order. These two requests are all GET requests from the client side, but with different parameters and purposes. If you just want to use .get() handler in this case you will need to define two view functions and register the two urls in url config. Or you can use ViewSet class or generic view with mixins that has action functions .list() and .retrieve() to handle these requests, then using router class to set the url configs that follows the REST url standards.