Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Alchemy: How to bulk update values from a list of dicts

I would like to update a table 'Salary' which has fields:

employeeId,
Salary

Now, I have updated values for each employee in a python dictionary, something like:

[
{employeeId:1,Salary:10000},
{employeeId:2,Salary:15000}
]

I am wondering if there is a way to do this update in a single SQL Alchemy update query rather than executing many update statements one by one

like image 583
ashu Avatar asked Apr 15 '16 00:04

ashu


1 Answers

I will assume that you already have the table mapped like Salary and that employeeId is your primary key. So, all you have to do, is use the same dict:

[
  {employeeId:1,Salary:10000},
  {employeeId:2,Salary:15000}
]

and use the function bulk_update_mappings

session.bulk_update_mappings(
                Salary,
                [{employeeId:1,Salary:10000},
                 {employeeId:2,Salary:15000}]
            )

In this function, the primary id is required to be in the dict because this will be your filter and the other keys (columns) will be updated with the value that you have defined in the dict.

PS: Sorry about my english.

like image 163
luisurrutia Avatar answered Oct 10 '22 19:10

luisurrutia