SQLAlchemy: filter by membership in at least one many-to-many related table(SQLAlchemy:通过至少一个多对多相关表中的成员资格过滤)
问题描述
使用 SQLAlchemy 0.7.1 和 MySQL 5.1 数据库,我建立了如下的多对多关系:
Using SQLAlchemy 0.7.1 and a MySQL 5.1 database, I've got a many-to-many relationship set up as follows:
user_groups = Table('user_groups', Base.metadata,
Column('user_id', String(128), ForeignKey('users.username')),
Column('group_id', Integer, ForeignKey('groups.id'))
)
class ZKUser(Base, ZKTableAudit):
__tablename__ = 'users'
username = Column(String(128), primary_key=True)
first_name = Column(String(512))
last_name = Column(String(512))
groups = relationship(ZKGroup, secondary=user_groups, backref='users')
class ZKGroup(Base, ZKTableAudit):
__tablename__ = 'groups'
id = Column(Integer, primary_key=True)
name = Column(String(512))
用户可以属于多个组,组可以包含多个用户.
Users can belong to multiple Groups, and Groups can contain multiple Users.
我想要做的是构建一个 SQLAlchemy 查询,该查询仅返回属于组列表中至少一个组的用户.
What I'm trying to do is build a SQLAlchemy query that returns only the Users who belong to at least one Group out of a list of Groups.
我使用了 in_ 函数,但这似乎只适用于测试列表中成员资格的标量值.我不是一个 SQL 编写者,所以我什至不知道这需要什么样的 SELECT 语句.
I played around with the in_ function, but that only seems to work for testing scalar values for membership in a list. I'm not much of a SQL writer, so I don't even know what kind of SELECT statement this would require.
推荐答案
好吧,经过大量研究,我意识到是我自己对 SQL 术语的无知阻碍了我.我寻找一种解决方案来查找属于至少一个"组列表的用户应该是找到属于任何"组列表的用户.来自 SQLAlchemy 的 any ORM 函数正是我所需要的,就像这样:
OK, after a lot of research, I realized that it was my own ignorance of SQL terminology that was holding me back. My search for a solution to find users belonging to "at least one of" the list of groups should have been to find users belonging to "any" of the list of groups. The any ORM function from SQLAlchemy does exactly what I needed, like so:
session.query(ZKUser).filter(ZKUser.groups.any(ZKGroup.id.in_([1,2,3])))
该代码发出此 SQL(在 MySQL 5.1 上):
That code emits this SQL (on MySQL 5.1):
SELECT * FROM users
WHERE EXISTS (
SELECT 1 FROM user_groups, groups
WHERE users.id = user_groups.contact_id
AND groups.id = user_groups.group_id
AND groups.id IN (%s, %s, %s)
)
这篇关于SQLAlchemy:通过至少一个多对多相关表中的成员资格过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQLAlchemy:通过至少一个多对多相关表中的成员资格过滤
基础教程推荐
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 在多列上分布任意行 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- oracle区分大小写的原因? 2021-01-01
