升级到Django REST framework 3.7
后,出现以下错误
File "/home/jpg/Projects/django2x/sample/views.py", line 24, in <module>
from rest_framework.filters import DjangoFilterBackend
ImportError: cannot import name 'DjangoFilterBackend'
这是我的看法
from rest_framework.filters import DjangoFilterBackend
from rest_framework import viewsets
class FooViewSet(viewsets.ModelViewSet):
queryset = Foo.objects.all()
serializer_class = Foo_Serializer
filter_backends = (DjangoFilterBackend,)
filter_fields = ('foo_bar', 'bar_foo')
最佳答案
rest_framework.filters.DjangoFilterBackend
在DRF : 3.7中被描述。因此,从DRF 3.7
开始,您应该安装django-filter软件包以在视图中使用DjangoFilterBackend
。
您可以将< DRF 3.6
样式过滤器更新为
from rest_framework import viewsets
from django_filters import rest_framework as filters
class FooViewSet(viewsets.ModelViewSet):
queryset = Foo.objects.all()
serializer_class = Foo_Serializer
filter_backends = (filters.DjangoFilterBackend,)
filterset_fields = ('foo_bar', 'bar_foo')
注意:在较新版本的django-filter中,
filter_fields
属性被更改为filterset_fields