Search code examples
pythonpeewee

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


Would it be possible to dynamically add filters to a Peewee select statement given a list? For example instead of:

Table.select().paginate(page,ENTRY_PER_PAGE).where((Table.Base==Base1) & (Table.Base==Base2) & ...)

I would like to pass in, say a list, and it would filter by content in that list:

list = [Base1, Base2, Base3...]
Table.select().paginate(page,ENTRY_PER_PAGE).where((Table.Base==contentfromList))

Solution

  • You can use 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 for b in base_list))
    )
    

    Instead of operator.and_ (operator.__and__), if you need to express more complex expression, you can also use lambda:

    ...
    reduce(lambda a, b: a & b, (Table.Base == b for b in base_list))
    ...