Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refreshing detached entity in sqlalchemy

I need to attach an object to session in such a way that it will not differ from one persisted in db. (Easier to explain it with code):

session.query(type(some_object)).filter_by(id=some_object.id).one()

Is there more proper way to do that? session.add(some_object) doesn't work since an entity with such id can already be attached to this session, and object = session.merge(some_object) doesn't work for me because it translates state from detached copy (if i make object.name='asdfasdf' these changes will be pending after merging object)

EDIT:

I found a bit less ugly way:

some_object = session.merge(some_object)
session.refresh(some_object)

But is there a way todo this in one call?

like image 600
Zozz Avatar asked Aug 31 '12 08:08

Zozz


People also ask

What does refresh do in 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.

What is Session flush in SQLAlchemy?

session. flush() communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction.

What does Session rollback () do?

Session. rollback() rolls back the current transaction.

What is Sessionmaker in SQLAlchemy?

Session in SQLAlchemy ORM However, to standardize how sessions are configured and acquired, the sessionmaker class is normally used to create a top-level Session configuration which can then be used throughout an application without the need to repeat the configurational arguments.


1 Answers

I need to attach an object to session in such a way that it will not differ from one persisted in db.

"will not differ from DB" pretty much means you're looking to load it, so query it. You might want to consider that the object might already be present in that target session. so your approach with query(type(object)) is probably the most direct, though you can use get() to hit the primary key directly, and populate_existing() to guarantee that state which already exists in the session is overwritten:

session.query(type(some_object)).populate_existing().get(some_object.id)

the above calls down to almost the same codepaths that refresh() does. The merge/refresh approach you have works too but emits at least two SELECT calls.

like image 149
zzzeek Avatar answered Sep 24 '22 04:09

zzzeek