检查SqlAlchemy

时间:2016-09-01 12:33:57

标签: sqlalchemy

假设我有一个分组的父/子关系,带有复合外键,如下所示:

class Group(Base):
    __tablename__ = 'group'
    id_ = Column('id', GUID, primary_key=True)

class Parent(Base):
    __tablename__ = 'parent'
    id_ = Column('id', GUID, primary_key=True)
    group_id = Column(GUID, ForeignKey('group.id'), primary_key=True)

    group = relationship(Group)

class Child(Base):
    __tablename__ = 'child'
    id_ = Column('id', GUID, primary_key=True)
    group_id = Column(GUID, ForeignKey('group.id'), primary_key=True)
    parent_id = Column(GUID)

    __table_args__ = (
        ForeignKeyConstraint(
            ['parent_id', 'group_id'],
            ['parent.id', 'parent.group_id']
        ),
    )

    group = relationship(Group)
    parent = relationship(Parent, foreign_keys=[parent_id], backref='children')

我的实际问题是:我如何找出连接条件是什么?我希望得到Child.parent.join_condition

之类的东西

加分点:Child.parent会产生这样的连接条件:ON (child.group_id = parent.group_id AND child.parent_id = parent.id)或者我是否需要明确并使用primaryjoin参数? 编辑我刚刚重新阅读this section of the docs,看起来好像不会。

1 个答案:

答案 0 :(得分:1)

在这种情况下,您无需使用primaryjoin。通过包含foreign_keys来定义group_id就足够了:

class Child(Base):
    ...
    parent = relationship(
        Parent,
        foreign_keys=[parent_id, group_id],
        backref='children',
    )

在这种情况下包括如下的连接:

q = session.query(Child).join(Parent)
print(q)

将产生:

SELECT  child.id AS child_id,
        child.group_id AS child_group_id,
        child.parent_id AS child_parent_id
FROM    child
JOIN    parent
    ON  parent.group_id = child.group_id
    AND parent.id = child.parent_id

注意:ON条件周围不需要括号。