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

时间:2014-04-14 07:31:29

标签: python sqlalchemy relationship declarative materialized-path-pattern

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

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。

1 个答案:

答案 0 :(得分:2)

使用最新的git master或0.9Al或更高版本的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]

注意这个模型,无论你是否处理"后代"或者" anscestors",使用集合。您希望将remote()foreign()放在一起,以便ORM将其视为一对多。