python - 如何在给定参数列表的情况下动态创建 where 子句?

标签 python peewee

是否可以动态地将过滤器添加到给定列表的 Peewee select 语句中?例如代替:

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

我想传入一个列表,它会按该列表中的内容进行过滤:

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

最佳答案

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

>>> 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))
)

代替operator.and_(operator.__and__),如果需要表达更复杂的表达式,也可以使用 lambda :

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

关于python - 如何在给定参数列表的情况下动态创建 where 子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26299666/

相关文章:

python - 将列表的 Pandas 数据框转换为数据框的字典

python - Pytest fixture 返回倍数

python - 如何在 python 中从 peewee 调用 mysql 过程

python - SQLAlchemy 中 peewee 的DoesNotExist 的等价物是什么?

python - 将 QML 信号连接到 PySide2 插槽

python - 如何让 Tkinter textarea 接受在 Python 3.X 上删除外部文件?

python - Python中类名后面括号之间的区域叫什么名字?

Python Peewee execute_sql() 示例

python - 使用 peewee 访问远程 MySQL 数据库

python - Peewee:如何选择 id 与列表匹配的多行?