我正在开发一个 Django 驱动的网站,该网站使用 django-filters,特别是 RangeFilter 来显示房地产的价格关系,并将其可视化为搜索表单上的滑块。
我的查询集最初在 PropertyListView 中形成为具有特定状态(销售或出租)的对象列表,然后将其传递给过滤器 PropertyFilter。
PropertyFilter 使用其他几个类来构造相应的小部件,例如价格滑块:
class PropertyFilter(FilterSet):
price = PriceFilter()
...
class PriceFilter(RangeFilter):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
values = [p.price for p in Property.objects.all()]
min_value = min(values)
max_value = max(values)
self.extra['widget'] = CustomRangeWidget(attrs={'label':_('Price, €'),'data-range_min':min_value,'data-range_max':max_value})
问题在于 PriceFilter 不“知道”查询集中有哪些对象,并且从完整的对象列表中获取价格音叉。这导致了尴尬的滑块,其音域太宽,从 600 到 300,000 欧元,这是无关紧要的。
我想让 PriceFilter 从查询集中获取价格。怎么可能做到呢?我尝试直接在此过滤器内使用查询集,将查询集传递到其中,或将状态作为 kwarg 参数传递,但每次我都会收到错误。
请帮助我,我被困住了。
您可以修改
PriceFilter
类以接受查询集并使用它来确定价格范围
class PriceFilter(RangeFilter):
def __init__(self, queryset=None, *args, **kwargs):
super().__init__(*args, **kwargs)
if queryset is not None:
values = [p.price for p in queryset]
min_value = min(values) if values else 0
max_value = max(values) if values else 0
self.extra['widget'] = CustomRangeWidget(attrs={'label': _('Price, €'), 'data-range_min': min_value, 'data-range_max': max_value})
else:
self.extra['widget'] = CustomRangeWidget(attrs={'label': _('Price, €'), 'data-range_min': 0, 'data-range_max': 0})
然后您将查询集从
PropertyListView
传递到 PropertyFilter
,然后传递到 PriceFilter
:
class PropertyFilter(FilterSet):
price = PriceFilter(queryset=Property.objects.filter(status='the_status_that_you_want_goes_here'))
# other filters
class Meta:
model = Property
fields = ['price', ...]
这样,
PriceFilter
将仅考虑过滤后的查询集中的价格,确保滑块反映适当的价格范围。
希望这对您有帮助。