有没有简单的方法可以做到这一点。我想我错过了一些组合。
search = request.GET.get(u'search')
cities = request.POST.getlist(u'cities')
countries = request.POST.getlist(u'countries')
if search and cities and counties:
self.object_list = self.get_queryset().filter(title__icontains=search, country__icontains=counties,
city__icontains=cities,)
elif search and cities:
self.object_list = self.get_queryset().filter(title__icontains=search, city__icontains=cities,)
elif search and counties:
self.object_list = self.get_queryset().filter(title__icontains=search, country__icontains=counties,)
elif cities and counties:
self.object_list = self.get_queryset().filter(country__icontains=counties, city__icontains=cities,)
elif search:
self.object_list = self.get_queryset().filter(title__icontains=search,)
elif search:
self.object_list = self.get_queryset().filter(title__icontains=search,)
else:
self.object_list = self.get_queryset()
基本上只传递所选的字段。
这是表格
search = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Looking For ...'}), required=False)
countries = forms.ModelMultipleChoiceField(queryset=Legs.objects.values_list('country', flat=True).distinct(),
widget=forms.CheckboxSelectMultiple(), required=False)
cities = forms.ModelMultipleChoiceField(queryset=Legs.objects.values_list('city', flat=True).distinct(),
widget=forms.CheckboxSelectMultiple(), required=False)
答案 0 :(得分:0)
您可以链接filter()
来电:
self.object_list = self.get_queryset()
if search:
self.object_list = self.object_list.filter(title__icontains=search)
if cities:
self.object_list = self.object_list.filter(city__icontains=cities)
if countries:
self.object_list = self.object_list.filter(country__icontains=countries)
答案 1 :(得分:0)
另一种方法是创建过滤器字典,然后在调用filter
时将其分解。
filters = {}
if search:
filters['title__icontains'] = search
if cities:
filters['city__icontains'] =cities
if countries:
filters['country__icontains'] =countries
self.object_list = self.get_queryset().filter(**filters)