python – 在SQL Alchemy中过滤关系
发布时间:2020-12-20 10:33:32 所属栏目:Python 来源:网络整理
导读:我有以下场景: class Author(Base): __tablename__ = 'author' id = Column(Integer,primary_key = True) name = Column(String) books = relationship('Books',backref='author')class Book(Base): __tablename__ = 'book' id = Column(Integer,primary_ke
我有以下场景:
class Author(Base): __tablename__ = 'author' id = Column(Integer,primary_key = True) name = Column(String) books = relationship('Books',backref='author') class Book(Base): __tablename__ = 'book' id = Column(Integer,primary_key = True) title = Column(String) 我想要做的是加载所有拥有包含SQL的书的作者 authors = session.query(Author) .join(Author.books) .filter(Book.title.like('%SQL%') .all() 看似简单. 我想做的是迭代作者并展示他们的作品 我如何构建我的查询,以便我过滤关系(即 解决方法
请阅读
Routing Explicit Joins/Statements into Eagerly Loaded Collections.然后使用
contains_eager ,您可以构建查询并获得您想要的内容:
authors = ( session.query(Author) .join(Author.books) .options(contains_eager(Author.books)) # tell SA that we load "all" books for Authors .filter(Book.title.like('%SQL%')) ).all() 请注意,您实际上是在欺骗sqlalchemy认为它已经加载了所有的Author.books集合,因此您的会话将知道有关世界真实状态的虚假信息. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |