title: SQLAlchemy - How to add dynamic left joins to a query?
body: <p>I have six tables, modeled like the following:</p>
  
  <pre><code>+--&lt; B &gt;--C
  | 
  A
  |
  +--&lt; D &gt;--E
  </code></pre>
  
  <p>I would like to be able to dynamically query any of these options:</p>
  
  <pre><code>A
  A, B, C
  A, D, E
  A, B, C, D E
  </code></pre>
  
  <p>For example, querying all four would look like</p>
  
  <pre><code>q = session.query(A, B, C, D, E) \
      .outerjoin(B, A.id == B.a_id).outerjoin(C, C.id == B.c_id)
      .outerjoin(D, A.id == D.a_id).outerjoin(E, E.id == D.e_id)
  </code></pre>
  
  <p>I can append the models to a list and dynamically use them in the <code>select</code> clause. However, I cannot figure out how to dynamically attach the joins. Here is what I have so far:</p>
  
  <pre><code>from sqlalchemy import outerjoin
  
  models = [A]
  joins = []
  
  if foo:
      models.append(B)
      models.append(C)
      joins.append(outerjoin(A, B, A.id == B.a_id))
      joins.append(outerjoin(B, C, C.id == B.c_id))
  
  if bar:
      models.append(D)
      models.append(E)
      joins.append(outerjoin(A, D, A.id == D.d_id))
      joins.append(outerjoin(D, E, E.id == D.e_id))
  
  q = session.query(*models)
  # How do I attach my joins list to this query?
  </code></pre>
  
  <p>I have tried the following, which did not work, and even if it did I would presume that the case when <code>foo</code> and <code>bar</code> are both <code>False</code> would leave an empty <code>FROM</code> clause.</p>
  
  <pre><code>q = q.select_from(*joins)
  </code></pre>
  
  <p>Of course I can get rid of the <code>joins</code> list and repeat the <code>if</code> conditions after executing <code>q = session.query(*models)</code>, like the following, but I would rather perform the conditional logic one time.</p>
  
  <pre><code>if foo:
      q = q.outerjoin(B, A.id == B.a_id).outerjoin(C, C.id == B.c_id)
  
  if bar:
      q = q.outerjoin(D, A.id == D.a_id).outerjoin(E, E.id == D.e_id)
  </code></pre>