1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| Parent 下添加 `children = relationship("Child", back_populates="parent")`
创建p1 = Parent()和c1 = Child()失败,原因是One or more mappers failed to initialize,即back_populates必须在关系两端同时指定
Parent下添加 `children = relationship("Child", back_populates="parent")` Child下添加 `parent = relationship("Parent", back_populates="children")`
Parent Attribute: Parent.children Parent.id Parent.metadata Parent.name Parent.query
Child Attribute: Child.id Child.metadata Child.name Child.parent Child.parent_id Child.query
p1 = Parent() c1 = Child() c1.parent = p1 or p1.children.append(c1)
Parent下添加 `children = relationship("Child", backref="parent")`
Parent Attribute: Parent.children Parent.id Parent.metadata Parent.name Parent.query
Child Attribute: Child.id Child.metadata Child.name Child.parent_id Child.query
p1 = Parent() c1 = Child() c1.parent = p1 or p1.children.append(c1)
可以看出使用backref时,实例化c1时会自动在c1对象上添加parent属性
此后再检查: hasattr(Child, 'parent') // True hasattr(c1, 'parent') // True hasattr(Parent, 'children') // True hasattr(p1, 'children') // True
Child 下添加 `parent = relationship("Parent", backref="children")` 情况和 3 相同 Parent下添加 `children = relationship("Child", backref="parent")` Child下添加 `parent = relationship("Parent", backref="children")`
创建p1 = Parent()和c1 = Child()失败,原因是One or more mappers failed to initialize 因此两者只能使用其中之一
lazy 指定如何加载相关记录,默认值是"select" select 首次访问时按需加载 immediate 源对象加载后就加载 joined 加载记录,但使用联结 subquery 立即加载,但使用子查询 noload 永不加载 dynamic 不加载记录,但提供加载记录的查询
lazy = "dynamic"只能用于collections,不立即查询出结果集,而是提供一系列结果集的方法,可以基于结果集再次进行更精确的查找
|