我正在使用django-filter。我有过滤器类:
class ProductFilter(django_filters.FilterSet):
def __init__(self, attribute=None, *args, **kwargs):
super(ProductFilter, self).__init__(*args, **kwargs)
#do stuff with attribute
和我的看法:
from django_filters.views import FilterView
class ProductListView(FilterView):
model = Product
....
filterset_class = ProductFilter
如何将参数传递给
ProductFilter
__init__
函数? filterset_class = ProductFilter(attribute='width')
不起作用。 最佳答案
您可以尝试覆盖get_filterset_kwargs
方法:
class ProductListView(FilterView):
model = Product
...
filterset_class = ProductFilter
def get_filterset_kwargs(self, filterset_class)
kwargs = super(ProductListView, self).get_filterset_kwargs(filterset_class)
kwargs['attribute'] = 'width'
return kwargs
在您的
FilterSet
类中,您可以从kwargs弹出属性:class ProductFilter(django_filters.FilterSet):
def __init__(self, **kwargs):
attribute = kwargs.pop['attribute']
super(ProductFilter, self).__init__(**kwargs)
或将其明确包含在签名中。
class ProductFilter(django_filters.FilterSet):
def __init__(self, attribute=None, **kwargs):
super(ProductFilter, self).__init__(**kwargs)