Combining multiple Django filters
So I'm struggling with filtering my products in Django. I currently have a search bar which works and the result of submutting a query ('whey' in this case) looks like this:
The thing I can't figure out is how to get the sort filter to work now ('Sorteer op:). Because when selecting an option my function in the view gets called, which looks like this:
def zoekopdracht(request):
if request.GET.get('search') != '':
try:
search = request.GET.get('search').lower()
queryset = models.Product.objects.annotate(search_name=Concat('title', Value(' '), 'categorie', 'brand'
, output_field=TextField()))
products = queryset.filter(search_name__icontains=search)
product_amount = len(products)
# sorteer filter
filtered = SortFilter(
request.GET,
queryset=products
)
# paginator
paginator = Paginator(filtered.qs, 12)
page = request.GET.get('page')
try:
response = paginator.page(page)
except PageNotAnInteger:
response = paginator.page(1)
except EmptyPage:
response = paginator.page(paginator.num_pages)
product_front_end = {
'final_products': response,
'filter': filtered,
'count': product_amount,
}
except AttributeError:
print(request.GET)
response = []
product_front_end = {
'final_products': response,
}
else:
response = []
product_front_end = {
'final_products': response,
}
return render(request, 'zoekopdracht.html', product_front_end)
Because the GET request from the search bar is empty now I lose the products. Is there a way to get the current products back to the view function? That way I can use my SortFilter on the current products.
urls.py:
urlpatterns = [
...
path('zoekopdracht', views.zoekopdracht, name='zoekopdracht'),
...
]
.html (search):
<div class="navbar" id="searchcontainer">
<form method="get" action="{% url 'zoekopdracht' %}" class="row search-input" id="demo-2" autocomplete="off">
<div class="col-md-12">
<input type="search" name="search" placeholder="Zoek.." id="searchinput">
</div>
</form>
</div>
.html (sort filter):
<form method="get" class="form-inline">
<select class="single-select" name="order_by" id="order_by" onchange="this.form.submit()">
<option>Sorteer op:</option>
<option value="-discount_sort">Hoogste korting</option>
<option value="new_price">Laagste prijs</option>
<option value="-new_price">Hoogste prijs</option>
</select>
</form>
filters.py:
class SortFilter(django_filters.FilterSet):
ORDER_BY_CHOICES = (
('-discount_sort', 'Hoogste korting'),
('-new_price', 'Hoogste prijs'),
('new_price', 'Laagste prijs'),
)
order_by = django_filters.ChoiceFilter(label='Sorteer op', choices=ORDER_BY_CHOICES, method='filter_by_order')
brand = django_filters.MultipleChoiceFilter(widget=forms.CheckboxSelectMultiple)
class Meta:
model = Product
fields = ['brand']
def filter_by_order(self, queryset, name, value):
return queryset.order_by(value)