python-3.x - 如何使用带有 where 子句多个过滤器的 sqlalchemy api 进行选择?
问题描述
我正在尝试编写一个通用方法,它应该接受过滤器字典作为键值对并使用支持多个 where 子句的 sqlalchemy 创建选择语句。
def _get_selected_field_value(self, table, fields, col_value=None):
"""Performs select Operation and gets the value of field.
Arguments:
table (sqlalchemy.Table) : table to select data from.
fields (list) : fields whose value to retrieve.
col_value (dict) : where column of table has value.
"""
stmt = db.select(fields).where(tuple_(*list(col_value.keys())).in_(list(col_value.values())))
但事实证明这是
(Pdb) str(stmt)
'SELECT host.name \nFROM host \nWHERE (:param_1) IN ((:param_2))'
这看起来不太对!
所以对于一个看起来像这样的表:
+----+-----------------+--------------+---------------+-------------------+
| id | name | user | ip_address | mac_address |
+----+-----------------+--------------+---------------+-------------------+
| 1 | DietPi | root | 192.168.0.151 | bx:2x:ex:bx:9x:6x |
+----+-----------------+--------------+---------------+-------------------+
我想
MariaDB [lan]> SELECT host.name from host WHERE host.user='root' and host.ip_address='192.168.0.151' ;
+--------+
| name |
+--------+
| DietPi |
+--------+
解决方案
请尝试以下代码:
stmt = db.select(fields).where(and_(*[column == value for column, value in col_value.items()]))
推荐阅读
- copy - 如何将克隆数据集的增量部分复制到zfs中的原始数据集(快照)?
- python - 如何在 Tkinter TTK 中更改特殊框架的颜色?
- javascript - 具有淡入覆盖和对话框的模态组件在动画结束前被禁用
- javascript - Retrofit 2.7.1 无法调用api请求
- mysql - 在 MySQL 中为每个用户记录访问日期时间和退出日期时间
- python - 将 CryptoJS Base64 编码转换为 Python
- javascript - 使用 j 查询计算表列中的重复值并在新 td 中显示为总重复值
- java - 如何使用任何加密算法加密 json 响应中的单个字段?
- javascript - 我想使用 JS 修改我的 JSON 输出
- mysql - 如何使用本地现有数据库进行棱镜?当我尝试时,出现以下错误