【发布时间】:2013-07-17 06:47:05
【问题描述】:
我希望能够通过 SQLAlchemy 中的多个多对多关系进行查询。
我有与组相关联的用户,这些组与角色相关联。所有关联都是多对多的。我想通过组获取与用户关联的角色列表。
这是我的精简模型:
class User(Model):
id = Column(Integer)
groups = relationship('Group', secondary=user_group)
class Group(Model):
id = Column(Integer)
roles = relationship('Role', secondary=role_group)
class Role(Model):
id = Column(Integer)
我对使用什么 SQL 有一个粗略的了解:
select distinct role.* from role, role_group
where role.id = role_group.role_id
and role_group.group_id in
(select "group".id from "group", user_group
WHERE user_group.user_id = 1
and "group".id = user_group."group.id")
但是我很难弄清楚如何将其转换为 SQLAlchemy...而且我不确定这里的 SQL 是否是执行此操作的最佳方法。
【问题讨论】:
标签: python sql sqlalchemy subquery