Wells
Wells

Reputation: 10969

SQLAlchemy & dynamically setting Table column values

Trying to do this:

meta = MetaData(bind=engine)
meta.reflect(bind=engine, schema='schema')
Mapper(Table, meta.tables['schema.table'])

t = Table("schema.table", meta, autoload=True, autoload_with=engine)
map = {'Col1': 'full_local_col1_name', 'Col2': 'full_local_col2_name'}

for remote, local in map.items():
    t.set(local, values[remote])

The idea being that values is a Dictionary object obtained from another service, and I am mapping the column names to my local table.

How can I accomplish this? SQLAlchemy's Table class has no set method.

Upvotes: 0

Views: 534

Answers (1)

doog abides
doog abides

Reputation: 2288

Not sure what you're trying to do.. Are you trying to insert, update, alter or something totally different? You can do this for insert.

meta = MetaData(bind=engine)
meta.reflect(bind=engine, schema='schema')
Mapper(Table, meta.tables['schema.table'])

t = Table("schema.table", meta, autoload=True, autoload_with=engine)
map = {'Col1': 'full_local_col1_name', 'Col2': 'full_local_col2_name'}

t.insert().values(**{local: values[remote] for remote, local in map.items()})

Upvotes: 1

Related Questions