Django(DRF):如何进行不区分大小写的排序

时间:2017-11-17 06:20:39

标签: django django-rest-framework

我有一个api with?ordering = name,type

我希望名称和类型都不区分大小写

class IngredientListAPIView(ListAPIView):
    queryset = Ingredient.objects.all()
    serializer_class = IngredientListSerializer
    filter_backends = [OrderingFilter]

1 个答案:

答案 0 :(得分:1)

https://github.com/encode/django-rest-framework/issues/3280

获得解决方案
from django.db.models.functions import Lower
from rest_framework.filters import OrderingFilter


class CaseInsensitiveOrderingFilter(OrderingFilter):

    def filter_queryset(self, request, queryset, view):
        ordering = self.get_ordering(request, queryset, view)

        if ordering:
            new_ordering = []
            for field in ordering:
                if field.startswith('-'):
                    new_ordering.append(Lower(field[1:]).desc())
                else:
                    new_ordering.append(Lower(field).asc())
            return queryset.order_by(*new_ordering)

        return queryset

然后在ListView中使用它

class IngredientListAPIView(ListAPIView):
    queryset = Ingredient.objects.all()
    serializer_class = IngredientListSerializer
    filter_backends = [SearchFilter,CaseInsensitiveOrderingFilter]
    search_fields = ['name','slug']