Reputation: 5837
I'm using the SQLAlchemy Python ORM in a Pylons project. I have a class "Project" which has a one to many relationship with another class "Entry". I want to do a query in SQLAlchemy that gives me all of the projects which have one or more entries associated with them. At the moment I'm doing:
[project for project in Session.query(Project) if len(project.entries)>0]
which I know isn't ideal, but I can't figure out how to do a filter that does what I require (e.g. Session.query(Project).filter(Project.entries.exists())).
Any ideas?
Upvotes: 15
Views: 4991
Reputation: 22668
Session.query(Project).filter(Project.entries.any())
should work.
Edited credit of James Brady's comment, be sure to give him some love.
Upvotes: 25