How can I update multiple, existing rows in a database, using dictionary that maps existing values for one column, to the required new values for another column?
I have a table:
class MyTable(BaseModel):
col1 = sa.Column(sa.String(256))
col2 = sa.Column(sa.String(256))
Given that col1
has already values and col2
is empty, how can I update col2
if I have the set of data as a dictionary:
payload = {'x': 'y', 'a': 'b', 'c': 'd'}
So this payload maps values for col1
, to a new value for col2
; after the update you'd get [{'col1': 'x', 'col2': 'y'}, ...]
from the database.
I tried a couple of ways, which actually work but I think they are not as optimal as it could be ex.:
my_table = MyTable.__table__
for key, value in payload.items():
stm = my_table.update()
stm = stm.where(getattr(sales_order_item.c, 'col1') == key)
stm = stm.values({'col2': value})
session.execute(stm)
Or like this
for key, value in payload.items():
query = session.query(MyTable).filter(MyTable.col1==key)
query.update({MyTable.col2: value})
Now both of these solutions work as expected the only thing that is bothering me is the time it takes, for example for a payload of 100 elements it takes up to 6 sec, and I'm almost sure that there should be a better way to do that, isn't it?
I was thinking if there is a way of making it work with the in_
function:
query(MyTable).filter(
MyTable.col1.in_(payload.keys())
)
but I don't know how to structure the update query.