Updating a row using SQLAlchemy ORM
I believe you are looking for something like this for your update query:
session.query(FoobarModel).filter(FoobarModel.id == foobar_id).update({'name': 'New Foobar Name!'})
Since update()
belongs to Query, and filter()
does return a Query
object, this will work, contrary to trying to call update()
on your FoobarModel
object (which does not have such a function) returned by Query.get()
, see also here.
As for looping over your properties and assigning them by name, you could do this with setattr
and a dict, like this:
foobar = session.query(FoobarModel).get(foobar_id)
props = {'name': 'my new name'}
for key, value in props.items():
setattr(foobar, key, value)
session.commit()
session.flush()
This is obviously a little pointless with just one property, but maybe it will come in handy at some point.