• django-filter version 2.0 改动


    今天使用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 the field_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']
    

    总结:

    遇到问题,先查阅官方文档最靠谱,问谁都白搭~~

  • 相关阅读:
    SealReport: 开放式数据库报表工具
    AngouriMath: 用于C#和F#的开源跨平台符号代数库
    Dapr v1.9.0 版本已发布
    .NET 7 发布的最后一个预览版Preview 7, 下个月发布RC
    腾讯云EKS 上部署 eshopondapr
    知乎问题:.NET AOT编译后能替代C++吗?
    几个Caller特性的妙用
    微信小程序模板消息测试 formId 的获取
    GIT 版本控制(每一次修改都是一个新的版本)
    (大表小技巧)有时候 2 小时的 SQL 操作,可能只要 1 分钟
  • 原文地址:https://www.cnblogs.com/wenqiangit/p/10222321.html
Copyright © 2020-2023  润新知