Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where/Filter from Table object using a Dictionary (or **kwargs)

I'm trying to update all Users in the users Table given some criteria.

update = ({"username" : "user1"}, {"address" : "1234", "password" : "newpass"})
users = Table(...)

I'm trying queries like:

users.update().where(**update[0]).values(update[1])
users.select().filter_by(**update[0]).update(update[1])

With a session, I know I could do:

session.query(Users).filter_by(**update[0])

Is there an analogue for a table object?

like image 611
user2411693 Avatar asked Feb 08 '23 10:02

user2411693


1 Answers

you can create where clauses list and pass it to where()

from sqlalchemy import and_

update = ({"username" : "user1"}, {"address" : "1234", "password" : "newpass"})

where_clauses = [users.c[key]==value for (key, value) in update[0].items()]
users.update().where(and_(*where_clauses)).values(**update[1])
like image 155
r-m-n Avatar answered Feb 12 '23 12:02

r-m-n