use paginate and filters in list method (Viewset)


To apply the filter_backends, filterset_class, ordering_fields, serializer_class, and pagination_class attributes to the list method in your View class, you can override the list method and apply the desired behavior.


Example code:

from rest_framework.response import Response
from rest_framework import status

class AnalysisListView(viewsets.ModelViewSet):
  # ...

  def list(self, request, *args, **kwargs):
    queryset = self.filter_queryset(self.get_queryset()) # Apply filters

    ordering = request.query_params.get('ordering')
    if ordering:
      ordering = ordering.split(',')
      queryset = queryset.order_by(*ordering) # Apply ordering

    page = self.paginate_queryset(queryset) # Paginate the queryset
    if page is not None:
      serializer = self.get_serializer(page, many=True)
      data = serializer.data
      # Add a dynamic field to each analysis in the serialized data
      for analysis_data in data:
        analysis_data['dynamic_field'] = 'Dynamic Value'
      return self.get_paginated_response(data)

    serializer = self.get_serializer(queryset, many=True)
    data = serializer.data
    # Add a dynamic field to each analysis in the serialized data
    for analysis_data in data:
      analysis_data['dynamic_field'] = 'Dynamic Value'
    return Response(data)


date:Nov. 29, 2023