声明式SQLAlchemy中的物化路径关系

2024-04-28 22:23:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个分层类别模型,其中层次结构是使用物化路径(每个级别一个字符)来维护的:

class Category(Base):
    __tablename__ = 'categories'

    id = Column(SmallInteger, primary_key=True)
    path = Column(String, unique=True, nullable=False)

    # problematic relationship
    all_subcats = relationship('Category', lazy='dynamic', viewonly=True,
                               primaryjoin=foreign(path).like(remote(path).concat('%')))

在试图定义“所有子类别”关系时,我遇到了一个问题:

^{pr2}$

SQLAlchemy很困惑,因为我加入了同一个专栏。我找到的所有例子都是在不同的列上连接的。在

这种关系有可能吗?我想通过这个连接进行查询,所以custom@property是不可接受的。在


Tags: path模型路径true层次结构关系分层column
1条回答
网友
1楼 · 发布于 2024-04-28 22:23:59

使用最新的git主机或SQLAlchemy版本0.9.5或更高版本。然后:

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Element(Base):
    __tablename__ = 'element'

    path = Column(String, primary_key=True)

    related = relationship('Element',
                           primaryjoin=
                                remote(foreign(path)).like(
                                        path.concat('/%')),
                           viewonly=True,
                           order_by=path)

e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)

sess = Session(e)
sess.add_all([
    Element(path="/foo"),
    Element(path="/foo/bar1"),
    Element(path="/foo/bar2"),
    Element(path="/foo/bar2/bat1"),
    Element(path="/foo/bar2/bat2"),
    Element(path="/foo/bar3"),
    Element(path="/bar"),
    Element(path="/bar/bat1")
])

e1 = sess.query(Element).filter_by(path="/foo/bar2").first()
print [e.path for e in e1.related]

请注意,无论您处理的是“后代”还是“anscestors”,此模型都使用集合。您需要将remote()foreign()放在一起,以便ORM将其视为一对多。在

相关问题 更多 >