我有两个与多对多相关的模型,其中一个是分层模型:
#hierarchical model
class Tag(Base):
__tablename__ = "tags"
id = Column(Integer, primary_key=True)
name = Column(String)
Tag.parent_id = Column(Integer, ForeignKey(Tag.id, ondelete='CASCADE'))
Tag.childs = relationship(Tag, backref=backref('parent', remote_side=[Tag.id]),
cascade="all, delete")
class Subject(Base):
__tablename__ = "subjects"
id = Column(Integer, primary_key=True, doc="ID")
name = Column(String)
tags = relationship(Tag, secondary="tags_subjects", backref="subjects")
#many-to-many relations model
class TagsSubjects(Base):
__tablename__ = "tags_subjects"
id = Column(Integer, primary_key=True)
tag_id = Column(Integer, ForeignKey("tags.id"))
subject_id = Column(Integer, ForeignKey("subjects.id"))
所以,我会尝试解释我想要做什么...我想做一个(或几个)查询,搜索所有主题的对象, 有'name'字段值的'foo'或者有相关标签,其名称的值如'foo' 或者具有相关标签的OR,具有一个或多个父级(或按层次结构的上方)标记带有'name'值,如'foo'
我试图这样做:
>>> subjects = session.query(Subject).filter(or_(
Subject.name.ilike('%{0}%'.format('foo')),
Subject.tags.any(
Tag.name.ilike('%{0}%'.format('foo')))
)).order_by(Subject.name).all()
但它不正确和“扁平”查询,没有分层功能:( 如何通过SQLAlchemy的API执行此操作? 谢谢!
P.S。我正在使用SQLite后端