ImportError:无法导入名称“ DjangoFilterBackend”

时间:2019-05-23 18:17:40

标签: django django-rest-framework django-filter

升级到 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')

1 个答案:

答案 0 :(得分:3)

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 >