1

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

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('%')))

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

sqlalchemy.exc.ArgumentError: Can't determine relationship direction for
relationship 'Category.all_subcats' - foreign key columns within the join
condition are present in both the parent and the child's mapped tables.
Ensure that only those columns referring to a parent column are marked as
foreign, either via the foreign() annotation or via the foreign_keys argument.

SQLAlchemy 很困惑,因为我正在加入同一列。我设法找到的所有示例总是加入不同的列。

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

4

1 回答 1

2

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

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]

请注意,无论您处理“后代”还是“祖先”,此模型都使用集合。您希望将其保持在一起remote()foreign()以便 ORM 将其视为一对多。

于 2014-04-19T22:52:13.747 回答