问题描述
我正在使用DRF(Django Rest Framework)。
I'm using DRF(Django Rest Framework).
我声明了ModelViewSet,现在我想在其上添加过滤器。
I declared a ModelViewSet, and now I want to add filters on that.
class GoodsViewSet(viewsets.ModelViewSet):
class Filter(FilterSet):
class Meta:
model = m.Goods
filter_class = Filter
filter_backends = (SearchFilter, Filter)
search_fields = ['name',]
queryset = m.Goods.objects.all()
serializer_class = s.GoodsSerializer
看到我声明了一个Filter子类并应用了它
Seeing that I declared a Filter sub class and applied it with:
filter_class = Filter
它在开始添加行之前就开始起作用:
It worked at the beginning, before I add the lines:
filter_backends = (SearchFilter, Filter)
search_fields = ['name',]
。
现在,在跳过普通 filter_class
的同时应用了搜索过滤器。
And now the search filter is applied while the normal filter_class
is skipped.
一个字,他们不能一起工作。
One word, they cannot work together.
如何解决这个问题?
推荐答案
最后,我发现我们应该一起指定两个 filter_backends
:
Finally, I found we should specify two filter_backends
together:
from rest_framework.filters import SearchFilter
from django_filters.rest_framework import DjangoFilterBackend
class GoodsViewSet(viewsets.ModelViewSet):
class Filter(FilterSet):
class Meta:
model = m.Goods
filter_class = Filter
filter_backends = (SearchFilter, DjangoFilterBackend)
search_fields = ['name',]
queryset = m.Goods.objects.all()
serializer_class = s.GoodsSerializer
或我们可以忽略特定 ViewSet
类上的 filter_backends
字段,但在 settings.py
:
Or we can ignore the filter_backends
field on a specific ViewSet
class, but apply them globally in settings.py
:
REST_FRAMEWORK = {
# ... other configurations
'DEFAULT_FILTER_BACKENDS': (
'rest_framework.filters.SearchFilter',
'django_filters.rest_framework.DjangoFilterBackend',
),
}
因此 filter_class
和 search_fields
选项可同时在ViewSet上使用。
So that the filter_class
and search_fields
options are available on the ViewSet at the same time.
这篇关于如何在Django Rest Framework上将正常Filter和SearchFilter一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!