I am using Django-filter app to construct search on my website. This is the code:
class PropertyFilter(django_filters.FilterSet):
city = django_filters.ModelMultipleChoiceFilter(queryset=City.objects.all(), widget = CheckboxSelectMultiple)
trade_type = django_filters.ModelMultipleChoiceFilter(queryset=Trade.objects.all(), widget = CheckboxSelectMultiple)
class Meta:
model = Property
fields = ['city', 'trade_type']
The problem is that when user marks two cities, Django-filter only filters objects via last URL parameter (city no. 2 in this casse):
http://example.org/lt/list/city=1&city=2
Models.py
:
class City(models.Model):
name = models.CharField(max_length=250, verbose_name=_('Name'))
Maybe I am doing something wrong ?
You could create a plural version of your query string and accept a list as the filter argument:
http://example.org/lt/list/?cities=1,2
class CustomFilterList(django_filters.Filter):
def filter(self, qs, value):
if value not in (None, ''):
values = [v for v in value.split(',')]
return qs.filter(**{'%s__%s' % (self.name, self.lookup_type): values})
return qs
class PropertyFilter(django_filters.FilterSet):
city = django_filters.ModelMultipleChoiceFilter(queryset=City.objects.all(), widget = CheckboxSelectMultiple)
trade_type = django_filters.ModelMultipleChoiceFilter(queryset=Trade.objects.all(), widget = CheckboxSelectMultiple)
cities = CustomFilterList(name="city", lookup_type="in")
class Meta:
model = Property
fields = ['cities', 'city', 'trade_type']
Check out this answer for filtering a list of values properly:
Possible to do an `in` `lookup_type` through the django-filter URL parser?