Sebastien Bruggeman
Sebastien Bruggeman

Reputation: 33

Flask SQLAlchemy add row using dynamic column name

I would like to add a row to an existing table but the column name is unknown. Earlier on in my script I have been able to use setattr() to update an existing entry and to query using getattr() - but I can't figure out how to add an new entry.

As an example: the ean and retailer_sku are read from a csv file, but, depending on the scripts inputs, the retailer column can have different values. I would like to avoid using several if-else statements.

ean='7622210496034'
retailer = 'gh'
retailer_sku = '8222868'
retailer_add = SkuRetailer(mainean=ean, retailer=retailer_sku)
db.session.add(retailer_add)

How can I use 'gh' instead of retailer in the constructor?

Upvotes: 1

Views: 670

Answers (1)

Ruben Helsloot
Ruben Helsloot

Reputation: 13139

To use variable keyword arguments (or kwargs), a common workaround is the following:

retailer = 'gh'
sku = '8222868'
kwargs = { 'mainean': ean, retailer: sku }
retailer_add = SkuRetailer(**kwargs)
db.session.add(retailer_add)

Upvotes: 1

Related Questions