【问题标题】:sqlalchemy relationship through an intermediate table通过中间表的sqlalchemy关系
【发布时间】:2017-03-18 09:22:09
【问题描述】:

我有三个相关的类:Parent、Child、SubChild。在这两种情况下,关系都是一对多的。我已经将它设置为child.parent 正确引用,当然sub_child.child.parent 也可以正常工作。

问题是我实际上不需要知道sub_child.child,但我确实需要知道 sub_child 的最终父级。我想建立一个关系,这样sub_child.parent 将返回对最终 Parent 对象的引用。

这可能吗,还是只是个坏主意?我已经阅读了文档,但没有看到太多看起来很有希望的内容。

我在 mysql 上使用 python2 和 sqlalchemy orm 作为后端。

【问题讨论】:

    标签: python sqlalchemy foreign-keys relationship


    【解决方案1】:

    看看http://docs.sqlalchemy.org/en/latest/orm/nonstandard_mappings.html

    使用此方法,您应该能够在您提到的三个表上创建映射,并将参与表的列作为属性分配给映射类。

    metadata = MetaData()
    
    parent = Table('parent', metadata,
            Column('id', Integer, primary_key=True),
            Column('child', Integer, ForeignKey('child.id')),
    )
    child = Table('child', metadata,
            Column('id', Integer, primary_key=True),
            Column('subchild', Integer, ForeignKey('subchild.id')),
    )
    subchild = Table('subchild', metadata,
            Column('id', Integer, primary_key=True),
            Column('some_column', String),
    )
    joined = join(parent, child, subchild)
    
    Base = declarative_base()
    
    class Parent(Base):
        __table__ = joined
    
        id = column_property(parent.c.id, child.c.id, subchild.c.id)
        subchild_attr = subchild.c.some_column
    

    【讨论】:

    • 有趣——这是否将查找任务卸载到数据库中,还是在 ORM 层中处理?作为替代方案,我正在考虑在类上定义一些简单的 getter 函数。
    • 是的,使用此映射器的查询将连接所有三个表,无需进一步努力。当然,您也可以使用“@property”“拉起”嵌套列,但您必须使用“joinedload”等查询选项以避免后续查询。如果您选择 getter 版本,请查看“@hybrid_property”装饰器。
    猜你喜欢
    • 2023-03-17
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 2017-11-22
    • 2014-03-09
    • 2016-08-17
    • 2021-03-26
    相关资源
    最近更新 更多