繁体   English   中英

如何动态创建给定参数列表的where子句?

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

给定一个列表,可以动态地将过滤器添加到Peewee select语句中吗? 例如,代替:

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

我想传入一个list ,它将按该list的内容进行过滤:

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

您可以使用reduce (在Python 3.x中为functools.reduce ):

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

使用生成器表达式:

base_list = [Base1, Base2, Base3]
Table.select().paginate(page,ENTRY_PER_PAGE).where(
    reduce(oeprator.and_, (Table.Base == b for b in base_list))
)

如果您需要表达更复杂的表达式,则可以使用lambda来代替operator.and_operator.__and__ )。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM