Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update an object after session.commit() in SQLAlchemy

Tags:

sqlalchemy

Does updating an object after issuing session.commit() works correctly? Or do I need to refresh the object?

I think this is sufficient for the question, but I may provide more information to clear my question if needed.

Edit:

By updating, I meant setting some attribute i.e. column values of the object.

like image 259
Shafiul Avatar asked Mar 12 '14 06:03

Shafiul


People also ask

How do I update data in SQLAlchemy?

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 commit do?

commit() commits (persists) those changes to the database. flush() is always called as part of a call to commit() (1). When you use a Session object to query the database, the query will return results both from the database and from the flushed parts of the uncommitted transaction it holds.

What does Session refresh do SQLAlchemy?

The Session. expire() and Session. refresh() methods are used in those cases when one wants to force an object to re-load its data from the database, in those cases when it is known that the current state of data is possibly stale.

Does commit close Session SQLAlchemy?

commit() is used to commit the current transaction. It always issues Session. flush() beforehand to flush any remaining state to the database; this is independent of the “autoflush” setting.


1 Answers

Short answer: No, you do not need to refresh manually, sqlalchemy will do it for you.


It is useful to know when it happens, so below is short overview. From documentation of Session.commit():

By default, the Session also expires all database loaded state on all ORM-managed attributes after transaction commit. This so that subsequent operations load the most recent data from the database. This behavior can be disabled using the expire_on_commit=False option to sessionmaker or the Session constructor.

Basically, given you did not set expire_on_commit=False, object will be refreshed automatically as soon as you try accessing (reading, not setting) its attributes after session.commit().

my_obj = session.query(MyType).get(1)
my_obj.field1 = 'value1'
session.commit() # will commit and expire my_obj

my_obj.field1 = 'new value' # object is still the same, but field is updated
print my_obje.field1 # at this point SA will first refresh the object from the database; and make sure that new values for changed fields are applied

In fact, if you enable logging, you will see that sqlalchemy emits new SELECT statements as soon as you access (read) persistant instances' attributes.

like image 134
van Avatar answered Sep 19 '22 13:09

van