如果你使用backref
您不需要在第二个表上声明关系。
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'))
如果你是not using backref
,并定义relationship
是分开的,那么如果你不使用back_populates
,sqlalchemy 不会知道如何连接关系,因此修改一个关系也会修改另一个关系。
因此,在您的示例中,您定义了relationship
是单独的,但没有提供back_populates
参数,修改一个字段不会自动更新交易中的另一个字段。
>>> parent = Parent()
>>> child = Child()
>>> child.parent = parent
>>> print(parent.children)
[]
看看它如何没有自动填写children
field?
现在,如果您提供back_populates
参数,sqlalchemy 将连接字段。
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
children = relationship("Child", back_populates="parent")
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id'))
parent = relationship("Parent", back_populates="children")
所以现在我们得到
>>> parent = Parent()
>>> child = Child()
>>> child.parent = parent
>>> print(parent.children)
[Child(...)]
Sqlalchemy 知道这两个字段现在是相关的,并且将在另一个字段更新时更新每个字段。值得注意的是,使用backref
也会这样做。使用back_populates
如果您想定义每个类上的关系,这很好,因此只需浏览模型类就可以轻松查看所有字段,而不必查看通过 backref 定义字段的其他类。