Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.5 kB
2
Indexable
Never
from rest_framework.filters import OrderingFilter
from django.db.models import F
from django.db.models.functions import Lower

class CustomFindingsOrdering(OrderingFilter):


    def filter_queryset(self, request, queryset, view):
        order_params = request.query_params.get(self.ordering_param)

        if not order_params:
            return queryset

        custom_ordering_fields = ['sla_days_remaining', '-sla_days_remaining']
        basic_ordering_fields = [
            'name', '-name',
            'jira_prod_task_key', '-jira_prod_task_key', 
            'jira_sec_task_key', '-jira_sec_task_key'
        ]

        fields = [param.strip() for param in order_params.split(',')]

        ordering = []
        for field in fields:
            if field in basic_ordering_fields or field in custom_ordering_fields:
                if field in ["name", "-name"]:
                    ordering.append(
                        Lower(F(field[1:])).desc(nulls_last=True) if field.startswith('-') else Lower(F(field)).asc(nulls_last=True)
                    )
                elif field.startswith('-'):
                    ordering.append(F(field[1:]).desc(nulls_last=True))
                else:
                    ordering.append(F(field).asc(nulls_last=True))

        if not ordering:
            return queryset            

        queryset = queryset.order_by(*ordering)

        return queryset