gpt4 book ai didi

python - 在 SQLAlchemy/Flask 中加入多个表

转载 作者:IT老高 更新时间:2023-10-28 20:27:16 24 4
gpt4 key购买 nike

我正在尝试找出 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 组成员
  • 1:n 成员项目
  • 1:n 版本项

我想通过从数据库中选择所有具有特定版本的 Item-Rows 来构造一个查询。然后我想按组订购,然后按成员(member)订购。使用 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)

但显然,这根本行不通。 Version 表上的连接操作似乎没有在两个表之间产生我预期的连接类型。也许我完全误解了这个概念,但是在阅读了教程之后,这对我来说是有意义的。

最佳答案

以下内容将在一个查询中为您提供所需的对象:

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',您可以通过查询来加载整个 对象网络(相对于上面的元组)的代码:

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

关于python - 在 SQLAlchemy/Flask 中加入多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21996288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com