Shuzheng
Shuzheng

Reputation: 14058

How can I check which objects are currently tracked by the Session in SQLAlchemy?

I know I can use the Session.new, Session.dirty, Session.deleted attributes to check objects that have been added, modified, or deleted from the Session.

However, after I've added an object o to the Session and committed, o won't show up in any of those Session attributes above, although o is still being tracked by the Session, i.e. subsequent modifications are reflected in Session.dirty.

s.add(o)
s.commit()
# s.new, s.dirty, s.deleted are now all empty (none contain o)

How can I see all objects tracked by the Session?

Upvotes: 3

Views: 1571

Answers (1)

SuperShoot
SuperShoot

Reputation: 10882

Individually you can check whether a single object is in the session using in:

if some_obj in session:
   do_something()

To see all tracked instances, you can inspect the identity_map, from the docs:

Iterating through Session.identity_map.values() provides access to the full set of persistent objects (i.e., those that have row identity) currently in the session.

Upvotes: 4

Related Questions