Andrew Mackie
Andrew Mackie

Reputation: 21

Using variables to refer to column names (SQLAlchemy ORM)

The SQLAlchemy ORM allows for:

instance1 = Class1()
instance1.foo = 'bar'

What I want to do, however, is refer the column name 'foo' by passing it as a variable to the instance, something like:

column_name = 'foo'
instance1[column_name] = 'bar'  # or
instance1.column(column_name) = 'bar'  # or
instance1.Column(column_name) = 'bar'

Or, perhaps to do something like:

instance1=Class1(foo='bar') # or
instance1=Class1('foo':'bar')

or:

dict = {'foo':'bar'}
instance1 = Class1(dict) # or
instance1 = Class1(**dict) # <-- THIS *DOES* WORK

None of the above work, of course. Is there a method of referring to the column name with a variable, please?

FYI, the bigger picture version of what I'm trying to do is to collect data into a dictionary with keys that match a subset of column names in multiple tables. Then I want to dump whatever I've gathered in the dictionary into those tables:

instance1 = Class1()
instance2 = Class2()
for key in data_dictionary:
   instance1[key] = data_dictionary[key]
   instance2[key] = data_dictionary[key]

or simply:

instance1 = Class1(data_dictionary)
instance2 = Class2(data_dictionary)

Thanks for your help, Andrew

Upvotes: 1

Views: 808

Answers (1)

Andrew Mackie
Andrew Mackie

Reputation: 21

Thank you, univerio - the following works:

dict = {'foo':'bar'}
instance = Class1(**dict)

As does your other suggestion:

setattr(instance, 'foo', 'bar')

Upvotes: 1

Related Questions