今天使用django-filter时候遇到了下面这个问题:
django-filter: TypeError at /goods/ init() got an unexpected keyword argument 'name'
I am learning Django REST Framework. And I want to use the django-filter in django rest framework to choose the result I want. I wrote a filter.py to get goods whose price is between pricemin and pricemax:
class GoodsFilter(filters.FilterSet):
pricemin = filters.NumberFilter(name="shop_price", lookup_expr='gte')
pricemax = filters.NumberFilter(name="shop_price", lookup_expr='lte')
class Meta:
model = Goods
fields = ['pricemin', 'pricemax']
then I used this filter in view.py:
class GoodsListViewSet(mixins.ListModelMixin,viewsets.GenericViewSet):
queryset = Goods.objects.all()
serializer_class = GoodsSerializer
pagination_class = GoodsPagination
filter_backends = (DjangoFilterBackend,)
filter_class = GoodsFilter
when I run my project, there is an error like this:
TypeError at /goods/
__init__() got an unexpected keyword argument 'name'
I did not use argument 'name' in my code, so I have no idea about this error. Traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/goods/
Django Version: 2.0.3
Python Version: 3.6.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'DjangoUeditor',
'users.apps.UsersConfig',
'goods.apps.GoodsConfig',
'trade.apps.TradeConfig',
'user_operation.apps.UserOperationConfig',
'crispy_forms',
'xadmin',
'rest_framework',
'django_filters']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:UsersHarryEnvs estvir2libsite-packagesdjangocorehandlersexception.py" in inner
35. response = get_response(request)
File "C:UsersHarryEnvs estvir2libsite-packagesdjangocorehandlersase.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:UsersHarryEnvs estvir2libsite-packagesdjangocorehandlersase.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:UsersHarryEnvs estvir2libsite-packagesdjangoviewsdecoratorscsrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "C:UsersHarryEnvs estvir2libsite-packages
est_frameworkviewsets.py" in view
103. return self.dispatch(request, *args, **kwargs)
File "C:UsersHarryEnvs estvir2libsite-packages
est_frameworkviews.py" in dispatch
483. response = self.handle_exception(exc)
File "C:UsersHarryEnvs estvir2libsite-packages
est_frameworkviews.py" in handle_exception
443. self.raise_uncaught_exception(exc)
File "C:UsersHarryEnvs estvir2libsite-packages
est_frameworkviews.py" in dispatch
480. response = handler(request, *args, **kwargs)
File "C:UsersHarryEnvs estvir2libsite-packages
est_frameworkmixins.py" in list
40. queryset = self.filter_queryset(self.get_queryset())
File "C:UsersHarryEnvs estvir2libsite-packages
est_frameworkgenerics.py" in filter_queryset
152. queryset = backend().filter_queryset(self.request, queryset, self)
File "C:UsersHarryEnvs estvir2libsite-packagesdjango_filters
est_frameworkackends.py" in filter_queryset
94. if not filterset.is_valid() and self.raise_exception:
File "C:UsersHarryEnvs estvir2libsite-packagesdjango_filtersfilterset.py" in is_valid
206. return self.is_bound and self.form.is_valid()
File "C:UsersHarryEnvs estvir2libsite-packagesdjango_filters
est_frameworkfilterset.py" in form
24. form = super().form
File "C:UsersHarryEnvs estvir2libsite-packagesdjango_filtersfilterset.py" in form
258. Form = self.get_form_class()
File "C:UsersHarryEnvs estvir2libsite-packagesdjango_filtersfilterset.py" in get_form_class
250. for name, filter_ in self.filters.items()])
File "C:UsersHarryEnvs estvir2libsite-packagesdjango_filtersfilterset.py" in <listcomp>
250. for name, filter_ in self.filters.items()])
File "C:UsersHarryEnvs estvir2libsite-packagesdjango_filtersfilters.py" in field
138. self._field = self.field_class(label=self.label, **field_kwargs)
File "C:UsersHarryEnvs estvir2libsite-packagesdjangoformsfields.py" in __init__
330. super().__init__(max_value=max_value, min_value=min_value, **kwargs)
File "C:UsersHarryEnvs estvir2libsite-packagesdjangoformsfields.py" in __init__
254. super().__init__(**kwargs)
Exception Type: TypeError at /goods/
Exception Value: __init__() got an unexpected keyword argument 'name'
原因如下
Filter.name renamed to Filter.field_name (#792)
The filter name has been renamed to
field_name
as a way to disambiguate the filter’s attribute name on its FilterSet class from thefield_name
used for filtering purposes.
So, from django-filter==2.0 onwards, use field_name instead of name
class GoodsFilter(filters.FilterSet):
pricemin = filters.NumberFilter(field_name="shop_price", lookup_expr='gte')
pricemax = filters.NumberFilter(field_name="shop_price", lookup_expr='lte')
class Meta:
model = Goods
fields = ['pricemin', 'pricemax']
总结:
遇到问题,先查阅官方文档最靠谱,问谁都白搭~~