Consider a simple model like this:

Library 1---* Shelf 1---* Book

Accordingly our model has the following relationships declared:

{tu wkelj kod z relationship wlaczajac backrefy)

We will write a query with a join to get all three objects at once

SELECT *
FROM Library
JOIN Shelf ON Library.id = Shelf.library_id
JOIN Shelf ON Shelf.id = Book.shelf_id
WHERE Library.name = 'TheLibrary' AND Shelf.loc = 'A1' AND Book.title
= 'Ender''s Game'

q = session.query(Library)
q = q.join(Shelf)
q = q.join(Book)
q = q.filter(Library.name = "TheLibrary")
q = q.filter(Shelf.loc = "A1")
q = q.filter(Book.title = "Ender's Game")
q = q.options(contains_eager('shelves', 'books'))
result = q.all()

Let's assume is only one record that meets the criteria (we have only
one book with this title on shelf A1). We expect to get a single
Library object with one-element collection of shelves, which has one
element colection of books. This is indeed what seems to come back.

However, upon access to a backref'd library _attribute_ in Shelf
object another database query again Library gets automatically
executed. This seems unneccesary because the related Library object is
already loaded into the session.

I've figured out that it has something to do with backref to from
Shelf to Library so I added a line:

q = q.options(contains_eager('shelves', 'Library'))

and now the supurios query does not run.

1. Are these backref paths required? It can get messy with deeper
relationships.
2. Indidentally accessing shelf attribute on Book DOES NOT result in a
query? Why this inconsitence or am I missing something?
3. How will create_eager behave with many-to-many relationship?

-- 
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