我需要限制已过滤的查询,因为它需要花费很多时间来执行。我知道django在添加过滤器后执行查询,所以这个解决方案非常合适。与此同时,我正在使用django-rest-framework,但我使用的代码片段非常简单。以下是视图的代码段示例:
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = (filters.DjangoFilterBackend,)
filter_fields = ('category', 'in_stock')
但是当我将其更改为Product.objects.all()[:10]
时,我收到错误。
使用django-rest和django-filters时是否可以侥幸逃脱?
以下是完整的追溯:
Traceback:
File "/Users/rod/Documents/htdocs/test3+/venv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/rod/Documents/htdocs/test3+/venv/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/Users/rod/Documents/htdocs/test3+/venv/lib/python3.5/site-packages/django/views/generic/base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "/Users/rod/Documents/htdocs/test3+/venv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
466. response = self.handle_exception(exc)
File "/Users/rod/Documents/htdocs/test3+/venv/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
463. response = handler(request, *args, **kwargs)
File "/Users/rod/Documents/htdocs/test3+/venv/lib/python3.5/site-packages/rest_framework/generics.py" in get
201. return self.list(request, *args, **kwargs)
File "/Users/rod/Documents/htdocs/test3+/venv/lib/python3.5/site-packages/rest_framework/mixins.py" in list
40. queryset = self.filter_queryset(self.get_queryset())
File "/Users/rod/Documents/htdocs/test3+/venv/lib/python3.5/site-packages/rest_framework/generics.py" in filter_queryset
151. queryset = backend().filter_queryset(self.request, queryset, self)
File "/Users/rod/Documents/htdocs/test3+/venv/lib/python3.5/site-packages/rest_framework/filters.py" in filter_queryset
73. return filter_class(request.query_params, queryset=queryset).qs
File "/Users/rod/Documents/htdocs/test3+/venv/lib/python3.5/site-packages/django_filters/filterset.py" in qs
375. qs = filter_.filter(qs, value)
File "/Users/rod/Documents/htdocs/test3+/venv/lib/python3.5/site-packages/django_filters/filters.py" in filter
87. qs = self.get_method(qs)(**{'%s__%s' % (self.name, lookup): value})
File "/Users/rod/Documents/htdocs/test3+/venv/lib/python3.5/site-packages/django/db/models/query.py" in filter
679. return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/rod/Documents/htdocs/test3+/venv/lib/python3.5/site-packages/django/db/models/query.py" in _filter_or_exclude
691. "Cannot filter a query once a slice has been taken."
Exception Type: AssertionError at /query/
Exception Value: Cannot filter a query once a slice has been taken.