Shafiul
Shafiul

Reputation: 2890

Update an object after session.commit() in 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.

Upvotes: 13

Views: 21020

Answers (1)

van
van

Reputation: 76962

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.

Upvotes: 17

Related Questions