What is the best way to load _all_ related entities into the session (recursively) of a given entity?

153 views
Skip to first unread message

alex

unread,
Nov 7, 2012, 2:48:18 AM11/7/12
to sqlal...@googlegroups.com
Hi all,

I have an entity fetched from the database.
Now I want to load its related entities recursively to be sure to have all reconstructed and living in the session.
I need this in order to expunge them and add them to another session.

joinedload(*) with appropiate join_depth settings in the relations takes too long and needs alot of memory.

Is there an option to do that implicitly on a loaded entity, because I do not want to invoke each single relation to load it explicitly?

Cheers,
Alex

Michael Bayer

unread,
Nov 7, 2012, 10:02:21 AM11/7/12
to sqlal...@googlegroups.com

On Nov 7, 2012, at 2:48 AM, alex wrote:

> Hi all,
>
> I have an entity fetched from the database.
> Now I want to load its related entities recursively to be sure to have all reconstructed and living in the session.
> I need this in order to expunge them and add them to another session.

This should not be necessary. If you expunge the lead object, but it's collections and related objects are unloaded, then they are not in the Session to be expunged in the first place; no load operation is needed. If, on the other hand, some collections or related objects are loaded, the "expunge" operation can be configured to cascade automatically by setting cascade="save-update, merge, expunge" on relationship(). The object as placed in the new session will load related collections and objects as needed where they will then be present in the new session. There's no need to actually have an object in the Session unless you are actually doing something with it, i.e. viewing it or modifying it, which directly implies that the object will have been loaded within that Session.


>
> joinedload(*) with appropiate join_depth settings in the relations takes too long and needs alot of memory.
>
> Is there an option to do that implicitly on a loaded entity, because I do not want to invoke each single relation to load it explicitly?

the style of loading can be configured on relationship() using the "lazy" parameter, but joined loading by default on relationship is not recommended in most cases, as joins by default gets in the way of writing performant queries.

A full description of loader strategies including techniques and things to consider is at: http://docs.sqlalchemy.org/en/latest/orm/loading.html
Reply all
Reply to author
Forward
0 new messages