在SQLAlchemy / Flask中加入多个表

时间:2014-02-24 18:45:25

标签: python join 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小组成员
  • 1:n会员项目
  • 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)

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

1 个答案:

答案 0 :(得分:34)

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

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

更新-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