Tuesday, 15 July 2014

python - How to dynamically create where clauses given a list of parameters? -



python - How to dynamically create where clauses given a list of parameters? -

would possible dynamically add together filters peewee select statement given list? illustration instead of:

table.select().paginate(page,entry_per_page).where((table.base==base1) & (table.base==base2) & ...)

i pass in, list, , filter content in list:

list = [base1, base2, base3...] table.select().paginate(page,entry_per_page).where((table.base==contentfromlist))

you can utilize reduce (functools.reduce in python 3.x):

>>> import operator >>> reduce(operator.mul, [2, 3, 5]) 30 >>> 2 * 3 * 5 30

with generator expression:

base_list = [base1, base2, base3] table.select().paginate(page,entry_per_page).where( reduce(oeprator.and_, (table.base == b b in base_list)) )

instead of operator.and_ (operator.__and__), if need express more complex expression, can utilize lambda:

... reduce(lambda a, b: & b, (table.base == b b in base_list)) ...

python peewee

No comments:

Post a Comment