I'm trying to create a function for updating rows in a database, based on an instance of a class.
Basically I would like to do something like this:
def update_table(self, result):
session = self.Session()
session.query(result.__class__).filter_by(id=result.id).update(result)
session.commit()
session.close_all()
user = db.Model.User(
id = 1,
name = "foo"
)
# Store user to db
db.save(user)
updated_user = db.Model.User(
id = 1,
user = "bar"
)
# Update the users name with id=1
update_table(updated_user)
The problem is ofc that the session query results in a
TypeError: 'User' object is not iterable
but in my mind, this should end up with an updated user with name="bar".
Is there way to create such a function using the SQLAlchemy ORM?
You don't need an extra update procedure ...
user = db.Model.User(
id = 1,
name = "foo"
)
# Store user to db
db.save(user)
new_user = session.query(User).filter(User.id==1).first()
new_user.name = "bar"
session.commit()
I ended up with this solution:
# Update single entry
def update_table_by_id(self, entry):
# Open connection to database
session = self.Session()
# Fetch entry from database
db_result = session.query(entry.__class__).filter_by(id=entry.id)
# Convert Models to dicts
entry_dict = entry.as_dict()
db_result_dict = db_result.first().as_dict()
# Update database result with passed in entry. Skip of None
for value in entry_dict:
if entry_dict[value] is not None:
db_result_dict[value] = entry_dict[value]
# Update db and close connections
db_result.update(db_result_dict)
session.commit()
session.close_all()
It allows me to send in arbitrary models, and they are all handled the same.
Suggestions and improvements are welcome!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.