"Django Rest Framework (DRF) provides powerful tools to build robust APIs. While the standard CRUD operations are usually sufficient, there are cases where you might need to add custom actions or endpoints to perform specific operations. This is where the @action decorator comes into play, allowing you to extend your ViewSets with additional functionalities. In this article, we will explore the concept of @action and demonstrate how to create custom actions using the GET and POST methods with practical code examples."
"Adding a Custom GET Action: Now, let's create a custom action that responds to a GET request. We'll implement a method called custom_get_action in our ViewSet and use the @action decorator to map it to the GET method: # myapp/views.py from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.viewsets import ViewSet class MyViewSet(ViewSet): # ... Standard ViewSet actions ... @action(detail=True, methods=['GET']) def custom_get_action(self, request, pk=None): # Custom action logic for GET request # Retrieve data or perform any operation based on the insta"
DRF ViewSets can be extended with the @action decorator to add custom endpoints alongside standard CRUD operations. Register the ViewSet with a router to expose default and custom routes. Use @action(detail=True or False, methods=[...]) to control whether the action applies to a single instance or a collection and which HTTP methods it accepts. Implement GET handlers to retrieve or compute data and return Response objects. Implement POST handlers to accept request.data, validate with serializers, save changes, and return appropriate Responses. Additional options include url_path, url_name, permission_classes, and serializer_class for fine-grained control.
Read at Djangocentral
Unable to calculate read time
Collection
[
|
...
]