在SQLAlchemy / Flask中联接多个表
我正在尝试找出SQLAlchemy中正确的联接查询设置,但似乎无法解决。
我有以下表格设置(简化后,我省略了非必要字段):
class Group(db.Model): id = db.Column(db.Integer, primary_key = True)
number = db.Column(db.SmallInteger, index = True, unique = True)
member = db.relationship('Member', backref = 'groups', lazy = 'dynamic')
class Member(db.Model):
id = db.Column(db.Integer, primary_key = True)
number = db.Column(db.SmallInteger, index = True)
groupid = db.Column(db.Integer, db.ForeignKey('group.id'))
item = db.relationship('Item', backref = 'members', lazy = 'dynamic')
class Version(db.Model):
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(80), index = True)
items = db.relationship('Item', backref='versions', lazy='dynamic')
class Item(db.Model):
id = db.Column(db.Integer, primary_key = True)
member = db.Column(db.Integer, db.ForeignKey('member.id'))
version = db.Column(db.Integer, db.ForeignKey('version.id'))
因此,关系如下:
- 1:n Group Member
- 1:n Member Item
- 1:n Version Item
我想通过从数据库中选择具有特定版本的所有项目行来构建查询。然后,我想按组然后按成员订购。使用Flask / WTForm的输出应如下所示:
* GroupA * MemberA
* ItemA (version = selected by user)
* ItemB ( dito )
* Member B
* ItemC ( dito )
....
我想出了类似以下查询的内容,但是我很确定它是不正确的(效率低下)
session.query(Item,Member,Group,Version) .join(Member).filter(version.id==1)
.order_by(Group).order_by(Member).all()
我的第一个直观方法是创建类似
Item.query.join(Member, Item.member==Member.id) .filter(Member.versions.name=='MySelection')
.order_by(Member.number).order_by(Group.number)
但显然,这根本不起作用。版本表上的联接操作似乎并未产生我期望的两个表之间的联接类型。也许我完全误解了这个概念,但是在阅读了教程之后,这对我来说很有意义。
回答:
以下将在一个查询中为你提供所需的对象:
q = (session.query(Group, Member, Item, Version) .join(Member)
.join(Item)
.join(Version)
.filter(Version.name == my_version)
.order_by(Group.number)
.order_by(Member.number)
).all()
print_tree(q)
但是,你得到的结果将是元组列表(Group, Member, Item, Version)
。现在由你决定以树形形式显示它。下面的代码可能被证明是有用的:
def print_tree(rows): def get_level_diff(row1, row2):
""" Returns tuple: (from, to) of different item positions. """
if row1 is None: # first row handling
return (0, len(row2))
assert len(row1) == len(row2)
for col in range(len(row1)):
if row1[col] != row2[col]:
return (col, len(row2))
assert False, "should not have duplicates"
prev_row = None
for row in rows:
level = get_level_diff(prev_row, row)
for l in range(*level):
print 2 * l * " ", row[l]
prev_row = row
Update-1:如果你愿意放弃lazy = 'dynamic'
前两个关系,则可以执行查询以object network
使用以下代码加载整个对象(与上述元组相对):
q = (session.query(Group) .join(Member)
.join(Item)
.join(Version)
# @note: here we are tricking sqlalchemy to think that we loaded all these relationships,
# even though we filter them out by version. Please use this only to get data and display,
# but not to continue working with it as if it were a regular UnitOfWork
.options(
contains_eager(Group.member).
contains_eager(Member.items).
contains_eager(Item.version)
)
.filter(Version.name == my_version)
.order_by(Group.number)
.order_by(Member.number)
).all()
# print tree: easy navigation of relationships
for g in q:
print "", g
for m in g.member:
print 2 * " ", m
for i in m.items:
print 4 * " ", i
以上是 在SQLAlchemy / Flask中联接多个表 的全部内容, 来源链接: utcz.com/qa/419096.html