In SQLAlchemy, can you filter a polymorphically associated model by the type of its associated record?
I'm using a polymorphic association in SQLAlchemy as described in this example. It can also be found in the examples directory in the SQLAlchemy source code.
Given this setup, I want to query for all Address
es that are associated with User
s. Not a user
but any user
.
In raw SQL, I could do that like this:
select addresses.* from addresses
join address_associations
on addresses.assoc_id = address_associations.assoc_id
where address_associations.type = 'user'
Is there a way to do this using the ORM Session?
Could I just run this raw SQL and then apply the Address class to ea开发者_Python百科ch row in the results?
ad-hoc joins using the ORM are described at:
http://www.sqlalchemy.org/docs/orm/tutorial.html#querying-with-joins
for address in sess.query(Address).join(Address.association).filter_by(type='users'):
print "Street", address.street, "Member", address.member
精彩评论