SQLAlchemy 中使用的 relationship() 函数是什么

Dar*_*awg 4 python flask flask-sqlalchemy

在阅读 SQLAlchemy 的文档时,我似乎无法理解 relationship() 函数的用途。

我已经创建了一个带有和不带有 relationship() 映射的数据库,并且在 db 级别的表定义中没有看到任何区别。我还注意到交互式提示对查询没有影响。表 'parent' 上没有创建 'children' 列。它的目的是什么?

 class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    children = relationship("Child", backref="parent")

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('parent.id'))
Run Code Online (Sandbox Code Playgroud)

dir*_*irn 9

relationship不影响数据库模式。它提供了一种访问相关对象的便捷方式。在这种情况下,它允许您通过属性获取Child与 a 相关的所有对象。然后为所有对象添加一个属性。ParentchildrenbackrefparentChild

默认情况下,相关对象将通过SELECT查询加载。但是,通过传递lazy='joined'relationship,这两个表将在查询时连接起来。


小智 5

dirn 的回答是正确的。举一些有用的例子:

session = Session()

# create children in a cool way
parent = Parent(children=[Child(), Child()])
# this will save everybody
session.add(parent)
session.commit()

# get every children of a parent is also simple now
parent = session.query(Parent).one()
print(parent.children)
Run Code Online (Sandbox Code Playgroud)