SQLAlchemy渴望加载递归模型

Sil*_*ver 5 python many-to-many sqlalchemy eager-loading

您如何编写一个渴望递归加载某个角色的父母和孩子的模型。因此,不仅是您现在要担任的角色的孩子,而且还是孩子。

您是否冒着无限循环结束的风险,还是SQLAlchemy具有检测这些逻辑的逻辑?

SQLAlchemy模型如下:

from sqlalchemy.ext.declarative import declarative_base


roles_parents = Table(
'roles_parents', Base.metadata,
Column('role_id', Integer, ForeignKey('roles.id')),
Column('parent_id', Integer, ForeignKey('roles.id'))
)


Base = declarative_base()
class Role(Base):

    __tablename__ = 'roles'

id = Column(Integer, primary_key=True)
name = Column(String(20))
parents = relationship(
    'Role',
    secondary=roles_parents,
    primaryjoin=(id == roles_parents.c.role_id),
    secondaryjoin=(id == roles_parents.c.parent_id),
    backref=backref('children', lazy='joined'),
    lazy='joined'
)

def get_children(self):
    logger.log_dbg("get_children(self) with name: "  + self.name)
    for child in self.children:
        yield child
        for grandchild in child.get_children():
            yield grandchild

@staticmethod
def get_by_name(name):
    logger.log_dbg("get_by_name( " + name + " )")
    with DBManager().session_scope() as session:
        role = session.query(Role).options(joinedload(
            Role.children).joinedload(Role.parents)).filter_by(
            name=name).first()
        # role = session.query(Role).filter_by(name=name).first()
        session.expunge_all()
        return role
Run Code Online (Sandbox Code Playgroud)

您可以看到,我尝试通过关系中的一个属性以及在获取角色的查询中的选项来启用对父关系的渴望加载。

需要这种急切的负载(和session.expunge_all())的原因是,当尝试通过get_children()获取子项时,会话丢失了。

由于急切的负载,访问此角色的子角色时,get_children不再失败。但是,在尝试获取孙子项时仍然失败。因此,渴望加载似乎适合于子角色,但并不渴望加载其子角色。

小智 0

我很好奇为什么你也想急切地加载孙子:用例是什么?

我问这个问题的原因是我假设您可以在需要时通过访问.children当前子节点上的属性来访问孙子节点。这应该减少内存负载(通过不递归地加载所有子节点),并且还使得处理当前节点(角色)更容易推理。