AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |
Back to Blog
Django rest framework post example11/13/2023 ![]() Notice that we've also used the decorator to create a custom action, named highlight. This time we've used the ModelViewSet class in order to get the complete set of default read and write operations. Permission_classes = renderer_classes=)ĭef highlight(self, request, *args, **kwargs): ![]() This viewset automatically provides `list`, `create`, `retrieve`,Īdditionally we also provide an extra `highlight` action. from rest_corators import actionįrom rest_framework.response import ResponseĬlass SnippetViewSet(viewsets.ModelViewSet): We can remove the three views, and again replace them with a single class. Next we're going to replace the SnippetList, SnippetDetail and SnippetHighlight view classes. We're still setting the queryset and serializer_class attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes. Here we've used the ReadOnlyModelViewSet class to automatically provide the default 'read-only' operations. This viewset automatically provides `list` and `retrieve` actions. We can remove the two views, and replace them with a single class: from rest_framework import viewsetsĬlass UserViewSet(viewsets.ReadOnlyModelViewSet): Let's take our current set of views, and refactor them into view sets.įirst of all let's refactor our UserList and UserDetail views into a single UserViewSet. ViewSet classes are almost the same thing as View classes, except that they provide operations such as retrieve, or update, and not method handlers such as get or put.Ī ViewSet class is only bound to a set of method handlers at the last moment, when it is instantiated into a set of views, typically by using a Router class which handles the complexities of defining the URL conf for you. REST framework includes an abstraction for dealing with ViewSets, that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions.
0 Comments
Read More
Leave a Reply. |