如何在sqlalchemy更新查询中添加自定义列名称?

时间:2019-07-11 14:12:01

标签: python python-3.x sqlalchemy

我有以下问题:

我在python方法中使用sqlalchemy,如下所示:

def update_icao_airport_id(self, airport_sys_id, project_sys_id, custom_column, value):
        """
        Updates Airport icao_airport_id value.
        :param airport_sys_id: airport_sys_id value you want to change
        :param project_sys_id: project_sys_id which is associated with Airport
        :param value: icao_airport_id new value
        :return: number of rows affected
        """
        query = AIRPORT.update(). \
            where(AIRPORT.c.airport_sys_id == airport_sys_id). \
            where(AIRPORT.c.project_sys_id == project_sys_id). \
            values(custom_column=value)
        result = self.execute_query(query)
        return result

我希望能够用方法中传递的参数替换'custom_column'。我无法使用列名,它仅适用于Airport_sys_id,project_sys_id和值的'='或'=='之后的值。

例如,我想传入方法(1、2,name_column,cat)并接收如下消息:

query = AIRPORT.update(). \
            where(AIRPORT.c.airport_sys_id == 1). \
            where(AIRPORT.c.project_sys_id == 2). \
            values(name_column=cat)

我竭尽所能,但没有成功。非常感谢您的支持。问候。

1 个答案:

答案 0 :(得分:0)

我的示例有一个可行的解决方案:

我们可以使用字典:

.values({custom_column: value})

然后我可以像这样在查询中使用它:

update_values = {custom_column: value}

query = AIRPORT.update(). \
        where(AIRPORT.c.airport_sys_id == airport_sys_id). \
        where(AIRPORT.c.project_sys_id == project_sys_id). \
        values(update_values)