我有一个api with?ordering = name,type
我希望名称和类型都不区分大小写
class IngredientListAPIView(ListAPIView):
queryset = Ingredient.objects.all()
serializer_class = IngredientListSerializer
filter_backends = [OrderingFilter]
答案 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']