Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update sqlalchemy orm object by a python dict

the dict's key names are mapping to the sqlalchemy object attrs

ex:

class User(Base):     __tablename__ = 'users'      id = Column(Integer, primary_key=True)     name = Column(String)     fullname = Column(String)     password = Column(String) 

can update from id = 3, {name: "diana"} or id = 15, {name: "marchel", fullname: "richie marchel"}

like image 218
chao787 Avatar asked Apr 18 '14 10:04

chao787


People also ask

How do I update SQLAlchemy in Python?

Update table elements in SQLAlchemy. Get the books to table from the Metadata object initialized while connecting to the database. Pass the update query to the execute() function and get all the results using fetchall() function. Use a for loop to iterate through the results.

What does SQLAlchemy refresh do?

You can use session. refresh() to immediately get an up-to-date version of the object, even if the session already queried the object earlier.


1 Answers

You can use setattr() to update attributes on an existing SQLAlchemy object dynamically:

user = session.query(User).get(someid)  for key, value in yourdict.items():     setattr(user, key, value) 
like image 186
Martijn Pieters Avatar answered Oct 11 '22 15:10

Martijn Pieters