Reputation: 2700
I have a list of keywords with an unknown number of elements like:
['key1', 'key2', 'key3']
I need to build a query using Peewee where a column name need to be %LIKE% either one of the words in the list.
SQL example:
SELECT *
FROM t
WHERE name LIKE '%key1%' OR
name LIKE '%key2%' OR
name LIKE '%key3%'
On the documentation it looks like I can build the query like so:
T.select().where(T.name ** 'key1' | T.name ** 'key2' | T.name ** 'key3')
This does not look can be built programmatically though...
How can I solve this issue?
Upvotes: 0
Views: 366
Reputation: 26245
Use reduce and the "or_" operator from the standard library:
clauses = [
(T.name ** 'key1'),
(T.name ** 'key2'),
(T.name ** 'key3')]
expr = reduce(operator.or_, clauses)
query = T.select().where(expr)
Upvotes: 3