本文介绍了Django(DRF):如何进行不区分大小写的排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有?ordering = name,type 的api
I have an api with ?ordering=name,type
我希望名称和类型都区分大小写
I want both the name and the type to be as case-insensitive
class IngredientListAPIView(ListAPIView):
queryset = Ingredient.objects.all()
serializer_class = IngredientListSerializer
filter_backends = [OrderingFilter]
推荐答案
从 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中使用它
then use it in the ListView
class IngredientListAPIView(ListAPIView):
queryset = Ingredient.objects.all()
serializer_class = IngredientListSerializer
filter_backends = [SearchFilter,CaseInsensitiveOrderingFilter]
search_fields = ['name','slug']
这篇关于Django(DRF):如何进行不区分大小写的排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!