在 SQLAlchemy 中查询多对多关系 [英] Querying a many-to-many relationship in SQLAlchemy

查看:52
本文介绍了在 SQLAlchemy 中查询多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常标准的多对多关系,类似于 ORM 教程中的博客 -> 关键字关系.

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')) 

然后我得到一个 'AND'/'EXISTS' 查询,这样只会返回包含所有这些关键字的帖子.是否有一种简单的方法可以将其作为或"查询来执行,或者我是否需要使用 join() 进行工作.

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.

推荐答案

我想你只是想要

.filter(Blog.keywords.any(Keyword.name.in_(['keyword1', 'keyword2', ...])))

我正在使用 http://www.sqlalchemy.org/docs/05/ormtutorial.html#common-filter-operators 供参考

这篇关于在 SQLAlchemy 中查询多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆