Querying a many-to-many relationship in SQLAlchemy
I have a pretty standard many-to-many relationship, similar to the Blog -> Keyword relationship in the ORM tutorial.
I would like to query for a list of Keywords, returning Blog posts where any of them match. However, I can't work out if there is a simple way to do this. If I add multiple filters, repeatedly doing
.filter(Blog.k开发者_运维技巧eywords.any(Keyword.name == 'keyword'))
then I get an 'AND'/'EXISTS' query, such that only posts which have all those keywords would be returned. Is there a simple way to do this as an 'OR' query, or do I need to work using join().
Thanks for any help; I can't work out whether I am missing something.
I think you just want
.filter(Blog.keywords.any(Keyword.name.in_(['keyword1', 'keyword2', ...])))
I'm using http://www.sqlalchemy.org/docs/05/ormtutorial.html#common-filter-operators for reference
精彩评论