我一直在尝试让OrderingFilter工作。从django-rest-framework页面的示例来看,它似乎应该相当简单:
class UserListView(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
filter_backends = (filters.OrderingFilter,)
ordering_fields = ('username', 'email')
但是,当我尝试这样做时:
from django_filters.rest_framework import DjangoFilterBackend, FilterSet, OrderingFilter
...
class ListingViewSet(viewsets.ModelViewSet):
queryset = Listing.objects.all()
serializer_class = ListingSerializer
filter_backends = (DjangoFilterBackend, OrderingFilter,)
filter_class = ListFilter
ordering_fields = ('price', 'views')
ordering = ('price',)
我得到一个关于OrderingFilter
没有filter_queryset
属性的错误:
ERROR 2016-11-13 03:14:57,304 log 25913 123145338523648 (<class 'AttributeError'>, AttributeError("'OrderingFilter' object has no attribute 'filter_queryset'",), <traceback object at 0x106ef48c8>)
Traceback (most recent call last):
File "/.../lib/python3.5/site-packages/rest_framework/views.py", line 474, in dispatch
response = handler(request, *args, **kwargs)
File "/.../lib/python3.5/site-packages/rest_framework/mixins.py", line 40, in list
queryset = self.filter_queryset(self.get_queryset())
File "/.../lib/python3.5/site-packages/rest_framework/generics.py", line 151, in filter_queryset
queryset = backend().filter_queryset(self.request, queryset, self)
AttributeError: 'OrderingFilter' object has no attribute 'filter_queryset'
进入OrderingFilter
,它确实没有filter_queryset
方法,但视图需要它:
# in GenericAPIView(views.APIView)
def filter_queryset(self, queryset):
"""
Given a queryset, filter it with whichever filter backend is in use.
You are unlikely to want to override this method, although you may need
to call it either from a list view, or from a custom `get_object`
method if you want to apply the configured filtering backend to the
default queryset.
"""
for backend in list(self.filter_backends):
queryset = backend().filter_queryset(self.request, queryset, self)
return queryset
我尝试了django rest framework queryset doesn't order中的各种解决方案,但似乎它们也不起作用。我尝试更新最有希望的答案:
class YOUR_VIEW_SET(viewsets.ModelViewSet):
#your code here
ordering_filter = OrderingFilter()
def filter_queryset(self, queryset):
queryset = super(YOUR_VIEW_SET, self).filter_queryset(queryset)
return self.ordering_filter.filter_queryset(self.request, queryset, self)
由于OrderingFilter
没有filter_queryset
方法,我将filter_queryset
更改为filter
(它确实有),但这个调用似乎与OrderingFilter
中filter
的签名冲突:
# In OrderingFilter(BaseCSVFilter, ChoiceFilter)
def filter(self, qs, value):
if value in EMPTY_VALUES:
return qs
ordering = [self.get_ordering_value(param) for param in value]
return qs.order_by(*ordering)
我不知道函数声明中的value
应该是什么,所以我可以尝试将其传递给函数,但似乎qs
引用了查询集,所以我假设它应该是第一个参数而不是第二个参数,但同样,我不完全确定value
是什么;因为它不是可迭代,所以似乎没有请求它。
我将感谢任何指针或想法,或变通办法,我道歉,如果我错过了一些明显的;我对Django不是很熟悉。
1条答案
按热度按时间pjngdqdw1#
我自己也碰到了!
不要使用django_filters中的类,使用
rest_framework.filters.OrderingFilter
。