Django REST Framework - Define extra arguments using the @action decorator

Django REST Framework - Define extra arguments using the @action decorator

In Django REST Framework (DRF), you can define extra arguments for a viewset method using the @action decorator from the rest_framework.decorators module. This allows you to add custom endpoints to your viewsets that can accept additional parameters.

Here's a basic example of how to use the @action decorator with extra arguments:

  1. Import Necessary Modules: Ensure you import the @action decorator from rest_framework.decorators.

  2. Define Your ViewSet: Use the @action decorator on a method within your viewset to create a custom endpoint.

  3. Handle Extra Arguments: Define the method to handle extra arguments.

Here's an example:

from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import status from .models import YourModel from .serializers import YourModelSerializer class YourModelViewSet(viewsets.ModelViewSet): queryset = YourModel.objects.all() serializer_class = YourModelSerializer @action(detail=True, methods=['get'], url_path='custom-action/(?P<param>\w+)') def custom_action(self, request, *args, **kwargs): # Extract the extra parameter from kwargs param = kwargs.get('param') # Perform your custom logic here # For example, you might filter queryset based on 'param' queryset = self.get_queryset().filter(some_field=param) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) 

Breakdown

  • @action Decorator:

    • detail=True means this action is meant for a single instance of the model (i.e., it uses an instance-specific URL).
    • methods=['get'] specifies that this action will respond to GET requests.
    • url_path='custom-action/(?P<param>\w+)' sets the custom URL path for this action, where (?P<param>\w+) is a named group in the URL pattern to capture the extra parameter.
  • custom_action Method:

    • Receives the extra parameter through kwargs.
    • Implements custom logic using the extra argument.
    • Returns a Response with the desired data.

URL Configuration

Ensure that the router for your viewset is properly configured in your URLs configuration:

from rest_framework.routers import DefaultRouter from .views import YourModelViewSet router = DefaultRouter() router.register(r'yourmodel', YourModelViewSet) urlpatterns = [ # Other URL patterns path('', include(router.urls)), ] 

In this setup, accessing /yourmodel/{id}/custom-action/{param}/ will invoke the custom_action method, allowing you to use the param value within that method.

Examples

  1. How to Use @action Decorator in Django REST Framework with Extra Query Parameters Description: Demonstrates how to define an action with additional query parameters using the @action decorator in Django REST Framework. Code:

    from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import viewsets from .models import MyModel from .serializers import MyModelSerializer class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer @action(detail=True, methods=['get']) def custom_action(self, request, pk=None): param = request.query_params.get('param', 'default') # Implement your logic here return Response({'param': param}) 

    Explanation: The custom_action method handles extra query parameters passed via the URL and responds with the value of param.

  2. Defining Custom Action with Extra Arguments Using @action Decorator in Django REST Framework Description: Shows how to create a custom action that accepts additional arguments and processes them. Code:

    from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import viewsets class ItemViewSet(viewsets.ViewSet): @action(detail=True, methods=['post']) def update_status(self, request, pk=None): status = request.data.get('status') # Process the status update return Response({'status': status}) 

    Explanation: The update_status action processes the status argument from the request data.

  3. Implementing an Action with URL Parameters Using @action in Django REST Framework Description: Demonstrates how to define a custom action that uses URL parameters with the @action decorator. Code:

    from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import viewsets class ProductViewSet(viewsets.ModelViewSet): @action(detail=False, methods=['get']) def filter_by_category(self, request): category = request.query_params.get('category') # Filter products by category return Response({'category': category}) 

    Explanation: filter_by_category action extracts the category parameter from the query string and uses it to filter results.

  4. Adding Custom Query Parameters to an Action with @action in Django REST Framework Description: Illustrates how to handle custom query parameters in a DRF action using the @action decorator. Code:

    from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import viewsets class OrderViewSet(viewsets.ModelViewSet): @action(detail=True, methods=['get']) def details(self, request, pk=None): start_date = request.query_params.get('start_date') end_date = request.query_params.get('end_date') # Process filtering by date range return Response({'start_date': start_date, 'end_date': end_date}) 

    Explanation: The details action handles custom date range parameters for filtering orders.

  5. Using @action Decorator to Add Additional Fields to Query in Django REST Framework Description: Shows how to add extra fields to the query parameters of an action. Code:

    from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import viewsets class UserViewSet(viewsets.ModelViewSet): @action(detail=False, methods=['get']) def search(self, request): username = request.query_params.get('username') email = request.query_params.get('email') # Search users by username or email return Response({'username': username, 'email': email}) 

    Explanation: The search action allows querying users by username or email.

  6. Defining a Custom Action with Extra Arguments Using @action Decorator Description: Demonstrates defining a custom action with additional arguments to handle specific use cases. Code:

    from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import viewsets class ReviewViewSet(viewsets.ModelViewSet): @action(detail=True, methods=['post']) def add_comment(self, request, pk=None): comment = request.data.get('comment') # Add a comment to a review return Response({'comment': comment}) 

    Explanation: The add_comment action handles a comment argument provided in the request data.

  7. Handling Extra Query Parameters in Custom Action Using @action in Django REST Framework Description: Illustrates how to handle additional query parameters in a custom action. Code:

    from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import viewsets class ArticleViewSet(viewsets.ModelViewSet): @action(detail=False, methods=['get']) def recent(self, request): days = request.query_params.get('days', '7') # Fetch recent articles based on days return Response({'days': days}) 

    Explanation: recent action processes the days parameter to filter articles.

  8. Creating an Action with Multiple Query Parameters Using @action in Django REST Framework Description: Shows how to create an action that handles multiple query parameters. Code:

    from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import viewsets class ReportViewSet(viewsets.ModelViewSet): @action(detail=False, methods=['get']) def generate(self, request): report_type = request.query_params.get('report_type') format = request.query_params.get('format') # Generate report based on type and format return Response({'report_type': report_type, 'format': format}) 

    Explanation: The generate action uses report_type and format parameters to generate a report.

  9. Customizing Actions with Extra Parameters Using @action Decorator in Django REST Framework Description: Demonstrates customizing an action with extra parameters to handle complex scenarios. Code:

    from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import viewsets class TaskViewSet(viewsets.ModelViewSet): @action(detail=True, methods=['post']) def assign(self, request, pk=None): user_id = request.data.get('user_id') due_date = request.data.get('due_date') # Assign task to user with a due date return Response({'user_id': user_id, 'due_date': due_date}) 

    Explanation: assign action takes user_id and due_date from request data to assign a task.

  10. Adding Parameters to @action Decorator Methods in Django REST Framework Description: Shows how to add and use parameters in @action decorator methods. Code:

    from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import viewsets class EventViewSet(viewsets.ModelViewSet): @action(detail=True, methods=['get']) def details(self, request, pk=None): include_past = request.query_params.get('include_past', 'false') # Get event details, optionally including past events return Response({'include_past': include_past}) 

    Explanation: The details action checks the include_past parameter to decide whether to include past events in the response.


More Tags

composite-key conditional-statements dart-2 python-requests aws-step-functions graphite hana picker hp-ux eonasdan-datetimepicker

More Programming Questions

More Statistics Calculators

More Entertainment Anecdotes Calculators

More Animal pregnancy Calculators

More Financial Calculators