简体   繁体   English

查询SQLAlchemy中的多对多关系

[英]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.我有一个非常标准的多对多关系,类似于 ORM 教程中的博客 -> 关键字关系。

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.然后我得到一个“AND”/“EXISTS”查询,这样只会返回包含所有这些关键字的帖子。 Is there a simple way to do this as an 'OR' query, or do I need to work using join().有没有一种简单的方法可以作为“或”查询来执行此操作,或者我是否需要使用 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 usinghttp://www.sqlalchemy.org/docs/05/ormtutorial.html#common-filter-operators for reference我正在使用http://www.sqlalchemy.org/docs/05/ormtutorial.html#common-filter-operators供参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM