1👍
you can modify the PriceFilter
class to accept the queryset and use it to determine the price range
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})
then you would pass the queryset from your PropertyListView
to the PropertyFilter
and subsequently to the PriceFilter
:
class PropertyFilter(FilterSet):
price = PriceFilter(queryset=Property.objects.none()) # initialize with an empty queryset
def __init__(self, data=None, queryset=None, *args, **kwargs):
if queryset is not None:
self.price = PriceFilter(queryset=queryset, *args, **kwargs)
super().__init__(data, queryset, *args, **kwargs)
# other filters
class Meta:
model = Property
fields = ['price', ...]
and now in your PropertyListView
you can pass the queryset to the PropertyFilter
:
class PropertyListView(ListView):
model = Property
def get_queryset(self):
queryset = Property.objects.filter(status='your_status_goes_here')
return queryset
def get_context_data(self):
context = super().get_context_data(**kwargs)
property_filter = PropertyFilter(data=self.request.GET, queryset=self.get_queryset())
context['filter'] = property_filter
return context
this way the PriceFilter
will consider only the prices from the filtered queryset ensuring that the slider reflects the appropriate price range.
I hope this helps you.
Source:stackexchange.com