Skip to content
Advertisement

Django – how to combine multiple filter parameters together, where the number of parameters is variable

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

table.objects.filter(col__icontains('a'))

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

query = 'a b c'
queryset = table.objects.all()
for part in query.split():
    queryset = queryset.filter(col__icontains=part)
Advertisement