On Aug 21, 2012, at 4:34 PM, adolfo wrote:
> Hi Michael and all....
>
> I successfully built a "all nodes" relationship following your guidelines.
>
> As:
>
> subq1=select([caso_vinculo.c.caso_1_id.label('id1'),caso_vinculo.c.caso_2_id.label('id2')]).union(select([caso_vinculo.c.caso_2_id, caso_vinculo.c.caso_1_id]))
> subq2=aliased(subq1)
>
> CasoMapper = mapper(Caso, caso, properties=
> {
> 'LinkedNodes':relation(Caso, secondary=subq2,
> primaryjoin=
caso.c.id == subq2.c.id1,
> secondaryjoin=subq2.c.id2==
caso.c.id),
> So with this property I can get both left and right linked nodes.
>
>
> with:
> CasoAlias=aliased(Caso)
> q1=session.query(Caso.id).outerjoin(CasoAlias.LinkedNodes)
> q1.all()
> works fine
> and once I add a new column from the aliased entity (CasoAlias)
> q2=q1.add_column(CasoAlias.id)
> it compiles fine
>
> SELECT
caso.id AS caso_id,
caso_1.id AS caso_1_id
> FROM caso AS caso_1 LEFT OUTER JOIN (SELECT caso_vinculo.caso_1_id AS id1, caso_vinculo.caso_2_id AS id2
> FROM caso_vinculo UNION SELECT caso_vinculo.caso_2_id AS caso_2_id, caso_vinculo.caso_1_id AS caso_1_id
> FROM caso_vinculo) AS anon_1 ON
caso_1.id = anon_1.id1 LEFT OUTER JOIN caso ON anon_1.id2 =
caso.id
there's a bug in SQLAlchemy here which I'll have fixed soon, it is somewhat hilarious though, the unusual naming scheme you're using for caso_vinculo's columns is conflicting with the labels SQLAlchemy is assigning. Note in the query, "
caso_1.id AS caso_1_id" at the top. Later on, when it renders "caso_vinculo.caso_1_id" in the subquery, it's erroneously stepping on the internal column record for the "caso_1_id" symbol and breaking things.
If you use different names on the caso_vinculo table for now it should be fine.