django_filters TypeError: __init__() got an unexpected keyword argument 'name'

2023-02-18 10:53:35 浏览数 (1)

# 错误信息:

代码语言:javascript复制
  File "E:py_virtualenvtracbuglibsite-packagesdjango_filtersrest_frameworkfilterset.py", line 24, in form
    form = super().form
  File "E:py_virtualenvtracbuglibsite-packagesdjango_filtersfilterset.py", line 258, in form
    Form = self.get_form_class()
  File "E:py_virtualenvtracbuglibsite-packagesdjango_filtersfilterset.py", line 250, in get_form_class
    for name, filter_ in self.filters.items()])
  File "E:py_virtualenvtracbuglibsite-packagesdjango_filtersfilterset.py", line 250, in <listcomp>
    for name, filter_ in self.filters.items()])
  File "E:py_virtualenvtracbuglibsite-packagesdjango_filtersfilters.py", line 140, in field
    self._field = self.field_class(label=self.label, **field_kwargs)
  File "E:py_virtualenvtracbuglibsite-packagesdjangoformsfields.py", line 228, in __init__
    super(CharField, self).__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'name'

# 解决方法

django-filter 参数名字已经由 name 更改为 field_name

代码语言:javascript复制
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
@author: yinzhuoqun
@site: http://zhuoqun.info/
@email: yin@zhuoqun.info
@time: 2019/10/18 18:54
"""

from .models import BugInfo
import django_filters



class BugsFilter(django_filters.rest_framework.FilterSet):
    """
    bug 的过滤类
    """
    # 老版本写法:name='xxx', 新版本要用 field_name='xxx'
    # views_max = django_filters.NumberFilter(name='num_views', lookup_expr='lte', help_text="最高浏览量过滤",
    #                                         label="浏览数量 小于等于此设置值")
    title = django_filters.CharFilter(field_name='title', lookup_expr='icontains', help_text="标题过滤",
                                      label="标题 不区分大小写过滤")

    class Meta:
        model = BugInfo
        fields = ["title", ]

0 人点赞