Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.keywords.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.

like image 260
somewhatoff Avatar asked Jul 01 '11 02:07

somewhatoff


1 Answers

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

like image 164
Mu Mind Avatar answered Oct 02 '22 09:10

Mu Mind