I have working code -- I just want to make sure I'm doing this the
best way.  If I have a graph of related objects, spanning numerous
tables and relationships, including many-to-many, and I want to
eagerly load the entire graph (rooted in some selected row or rows of
one of the tables) in a single query, I can do something like this:

(In this example, B and C have a many-to-many relationship containing
extra fields on the relationship table, with BC as the association
object.  The other relationships are either one-to-many or many-to-one
-- both seem to work the same way for this purpose.).

session.query(A, B, BC, C, D, E).join(B, BC, C, D,
E).filter(A.id==someId).options(contains_eager(A.b, B.bc, BC.c, C.d,
D.e))

That seems to work.  It gives me a big honkin' query with inner joins,
returning a number of rows equal to the number of E's in the graph
rooted at A.id==someId.  Each row contains all columns of all the
tables.  In my particular application at least, it is faster to do it
this way than to load each relation lazily, in the case where it's all
going to be loaded anyway.  My question is simply -- is there a better
way?  I chose contains_eager so that I could make the joins all inner
joins, because in my case I don't need to worry about rows higher up
in the chain that don't have corresponding rows further down.  I
suppose I could simplify my code -- presumably at the expense of
execution time -- if I just used joinedload instead, and let SA make
it a big outer join.  It just seems like a rather verbose way to tell
SA "please just eagerly follow all relationships as far as they lead
you" -- is there a shortcut?

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to