I’m trying to implement a search function on Django. If my query is: “a b c”, then I want to to search :
select * from table where col LIKE '%a%' and col LIKE '%b%' and col LIKE '%c%'
I see I can do that with
JavaScript
x
2
1
table.objects.filter(col__icontains('a'))
2
But how do I make this work for a,b & c. I can’t hard-code the number of parameters. There might be a,b,c,d or any number of search terms.?
Advertisement
Answer
You can chain filters on a QuerySet in a loop to get multiple AND
filters
JavaScript
1
5
1
query = 'a b c'
2
queryset = table.objects.all()
3
for part in query.split():
4
queryset = queryset.filter(col__icontains=part)
5