首页 > 解决方案 > 如何使用带有 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 |
+--------+

标签: python-3.xsqlalchemywhere-clause

解决方案


请尝试以下代码:

stmt = db.select(fields).where(and_(*[column == value for column, value in col_value.items()]))

推荐阅读