Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy - full load instance before detach

is there a way how to fully load some SQLAlchemy ORM mapped instance (together with its related objects) before detaching it from the Session? I want to send it via pipe into another processs and I don't want to merge it into session in this new process.

Thank you
Jan

like image 287
honzas Avatar asked Nov 06 '22 15:11

honzas


1 Answers

I believe you'll want to use the options() method on the Query, with eagerload() or eagerload_all().

Here's an example of use from one of our apps, where the class Controlled has a relation called changes which brings in a bunch of DocumentChange records, which themselves have a relation dco that brings in one Dco object per instance. This is a two-level eager-load, thus the use of the eagerload_all(). We're using the declarative extension (in case that matters) and m.Session is a "scoped" (thread-local) session.

from sqlalchemy.orm import eagerload, eagerload_all
...
controlled_docs = (m.Session.query(m.Controlled)
    .options(eagerload_all('changes.dco'))
    .order_by('number')
    .all())

If that's not sufficient, perhaps include a snippet or text showing how the relevant ORM classes are related and I could update the answer to show how those options would be used in your case.

like image 120
Peter Hansen Avatar answered Nov 12 '22 17:11

Peter Hansen