Question

This is a duplicate of this question, but I don't understand the answer. I think it is flawed, because this query:

session.query(Base).join(Base.owner).order_by(Player.name)

results in duplicate joins:

  1. joins coming from relationships (lazy='joined') specified on Base class
  2. joins specified in the query

Base table is joined with 5 copies of Player table. This does not look too efficient!

At least this is the way it seems to work in SQL Alchemy 0.9.1.

Does anyone have a better answer to that question?

Was it helpful?

Solution

This is on purpose and is documented here: http://docs.sqlalchemy.org/en/rel_0_9/orm/loading.html?highlight=eagerload#contains-eager

Populating relationships is separate from joining for filtering by default. To cut down on the duplicate joins, you can use query.options(contains_eager(Base.owner) to make the join populate the relationship.

Since you say there are five joins appearing, I assume you have other relationships with lazy='joined', those will by definition need a join one way or another. contains_eager just cuts down on duplicates in some situations. Another solution is to set lazy='select' (or not have it at all) to make the relation lazy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top