In SqlAlchemy, how to retrieve a column only by its name?

Viewed 18

In SqlAlchemy, we normally do the following in order to update a table:

result = conn.execute(
    update(my_table).where( my_table.c.table_name == "Example"),
    [
        values_to_update
    ]
)

But, unfortunately I cannot use "my_table.c.table_name", because "table_name" is supposed to change dynamically in my code.

The only value I can use is the string "table_name".

So I guess my question is: how do I retrieve a table by using its name (accessible by a string) (instead of calling "my_table.c.table_name").

Hope this is not confusing

Thanks a lot

1 Answers

Assuming table_name is actually a column of your table in this example, you can use

.where(getattr(my_table, table_name) == "Example")
Related