gpt4 book ai didi

python - 声明式 SQLAlchemy 中的具体化路径关系

转载 作者:行者123 更新时间:2023-12-01 05:16:42 26 4
gpt4 key购买 nike

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

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是 Not Acceptable 。

最佳答案

使用最新的 git master 或 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]

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

关于python - 声明式 SQLAlchemy 中的具体化路径关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23054398/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com