如何在 SQLAlchemy Core 中将列名作为参数传递?

luk*_*kik 6 python sqlalchemy python-3.x

我有一个 sqlalchemy 核心批量更新查询,我需要以编程方式传递要更新的列的名称。

该函数如下所示,每个变量都有注释:

def update_columns(table_name, pids, column_to_update):
    '''
    1. table_name: a string denoting the name of the table to be updated
    2. pid: a list of primary ids
    3. column_to_update: a string representing the name of the column that will be flagged. Sometimes the name can be is_processed or is_active and several more other columns. I thus need to pass the name as a parameter.
    '''
    for pid in pids:
        COL_DICT_UPDATE = {}
        COL_DICT_UPDATE['b_id'] = pid
        COL_DICT_UPDATE['b_column_to_update'] = True
        COL_LIST_UPDATE.append(COL_DICT_UPDATE)

    tbl = Table(table_name, meta, autoload=True, autoload_with=Engine)
    trans = CONN.begin()
    stmt = tbl.update().where(tbl.c.id == bindparam('b_id')).values(tbl.c.column_to_update==bindparam('b_column_to_update'))
    trans.commit()
Run Code Online (Sandbox Code Playgroud)

table参数被接受并且工作正常。

column_to_update当作为参数传递不起作用。它因错误而失败raise AttributeError(key) AttributeError: column_to_mark。但是,如果我对列名进行硬编码,则查询将运行。

如何传递column_to_updateSQLAlchemy的名称来识别它?

编辑:最终脚本

感谢@Paulo,最终脚本如下所示:

def update_columns(table_name, pids, column_to_update):
    for pid in pids:
        COL_DICT_UPDATE = {}
        COL_DICT_UPDATE['b_id'] = pid
        COL_DICT_UPDATE['b_column_to_update'] = True
        COL_LIST_UPDATE.append(COL_DICT_UPDATE)

    tbl = Table(table_name, meta, autoload=True, autoload_with=Engine)         
    trans = CONN.begin()
    stmt = tbl.update().where(
                              tbl.c.id == bindparam('b_id')
                              ).values(**{column_to_update: bindparam('b_column_to_update')})
    CONN.execute(stmt, COL_LIST_UPDATE)
    trans.commit()
Run Code Online (Sandbox Code Playgroud)

Pau*_*ine 5

我不确定我是否理解您想要什么,并且您的代码看起来与我认为惯用的 sqlalchemy 非常不同(我不是批评,只是评论我们可能使用正交代码样式)。

如果要将文字列作为参数传递,请使用:

from sqlalchemy.sql import literal_column
...
tbl.update().where(
    tbl.c.id == bindparam('b_id')
).values({
    tbl.c.column_to_update: literal_column('b_column_to_update')
})
Run Code Online (Sandbox Code Playgroud)

如果要动态设置表达式的右侧,请使用:

tbl.update().where(
    tbl.c.id == bindparam('b_id')
).values({
    getattr(tbl.c, 'column_to_update'): bindparam('b_column_to_update')
})
Run Code Online (Sandbox Code Playgroud)

如果这些都不是您想要的,请对答案发表评论或改进您的问题,我会尽力提供帮助。

[更新]

values命名参数方法的用途喜欢.values(column_to_update=value)那里column_to_update是实际的列名,而不是一个变量保存列名。例子:

stmt = users.update().\
        where(users.c.id==5).\
        values(id=-5)
Run Code Online (Sandbox Code Playgroud)

请注意,where使用比较运算符==values使用归因运算符=- 前者在布尔表达式中使用列对象,而后者使用列名作为关键字参数绑定。

如果您需要它是动态的,请使用**kwargs符号:.values(**{'column_to_update': value})

但可能您想使用values参数而不是values方法。