我正在使用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')
不起作用。
答案 0 :(得分:2)
您可以尝试覆盖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)