当数据很多时 SearchFilter 行为不当
当我有大约 10 条记录时,我测试了 SearchFilter,它工作正常,但是当数据记录超过 200 条时,我继续测试它,它只返回相同的数据,而不搜索或过滤数据,下面是我的视图文件:
class PostList(generics.ListCreateAPIView):
"""Blog post lists"""
queryset = Post.objects.filter(status=APPROVED)
serializer_class = serializers.PostSerializer
authentication_classes = (JWTAuthentication,)
permission_classes = (PostsProtectOrReadOnly, IsMentorOnly)
filter_backends = [DjangoFilterBackend, filters.SearchFilter]
filter_fields = ('title', 'body', 'description',)
search_fields = (
'@title',
'@body',
'@description',
)
def filter_queryset(self, queryset):
ordering = self.request.GET.get("order_by", None)
author = self.request.GET.get("author", None)
if ordering == 'blog_views':
queryset = queryset.annotate(
address_views_count=Count('address_views')).order_by(
'-address_views_count')
if author:
queryset = queryset.filter(owner__email=author)
return queryset
这就是我搜索的方式:
/api/v1/blogs/?search=an+elephant
但它只是返回所有数据而不是过滤。
I tested the SearchFilter when I had around 10 records , and it was working fine, but I went ahead and tested it when the data records are above 200, it just returning the same data without searching or filtering the data , below is my View file :
class PostList(generics.ListCreateAPIView):
"""Blog post lists"""
queryset = Post.objects.filter(status=APPROVED)
serializer_class = serializers.PostSerializer
authentication_classes = (JWTAuthentication,)
permission_classes = (PostsProtectOrReadOnly, IsMentorOnly)
filter_backends = [DjangoFilterBackend, filters.SearchFilter]
filter_fields = ('title', 'body', 'description',)
search_fields = (
'@title',
'@body',
'@description',
)
def filter_queryset(self, queryset):
ordering = self.request.GET.get("order_by", None)
author = self.request.GET.get("author", None)
if ordering == 'blog_views':
queryset = queryset.annotate(
address_views_count=Count('address_views')).order_by(
'-address_views_count')
if author:
queryset = queryset.filter(owner__email=author)
return queryset
This is how I search :
/api/v1/blogs/?search=an+elephant
But it just returns back all the data instead of filtering.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您覆盖了
filter_queryset
,因此它将不再与filter_backends
配合使用来过滤数据。您应该通过进行超级调用来进一步过滤查询集:Because you made an override of the
filter_queryset
, it will no longer work with thefilter_backends
to filter the data. You should filter the queryset further, by making a super call: