Filtering with joined tables

Posted by viraptor on Stack Overflow See other posts from Stack Overflow or by viraptor
Published on 2012-03-22T11:26:37Z Indexed on 2012/03/22 11:29 UTC
Read the original article Hit count: 171

Filed under:
|
|
|
|

I'm trying to get some query performance improved, but the generated query does not look the way I expect it to.

The results are retrieved using:

query = session.query(SomeModel).
        options(joinedload_all('foo.bar')).
        options(joinedload_all('foo.baz')).
        options(joinedload('quux.other'))

What I want to do is filter on the table joined via 'first', but this way doesn't work:

query = query.filter(FooModel.address == '1.2.3.4')

It results in a clause like this attached to the query:

WHERE foos.address = '1.2.3.4'

Which doesn't do the filtering in a proper way, since the generated joins attach tables foos_1 and foos_2. If I try that query manually but change the filtering clause to:

WHERE foos_1.address = '1.2.3.4' AND foos_2.address = '1.2.3.4'

It works fine. The question is of course - how can I achieve this with sqlalchemy itself?

© Stack Overflow or respective owner

Related posts about python

Related posts about sql