如何查询 SQLAlchemy 对象实例中的一对多关系?

Nat*_*ord 5 python sqlalchemy python-3.x

假设我有以下内容(在 Python 3 和 SQLAlchemy 中):

class Book(Base):
    id = Column(Integer, primary_key=True)
    chapters = relationship("Chapter", backref="book")

class Chapter(Base):
    id = Column(Integer, primary_key=True)
    name = Column(String)
    book_id = Column(Integer, ForeignKey(Book.id))

def check_for_chapter(book): 
    # This is where I want to check to see if the book has a specific chapter.
    for chapter in book.chapters:
        if chapter.name == "57th Arabian Tale"
            return chapter
    return None
Run Code Online (Sandbox Code Playgroud)

这感觉像是一种“非惯用”方法,因为它似乎不太可能利用数据库来搜索给定的章节。在最坏的情况下,似乎会n调用 db 来检查章节标题,尽管我对 SQLAlchemy 的有限理解表明可以对其进行配置。我不知道是否有办法直接针对您已经获取的对象的关系发起查询?如果是这样,如何做到这一点?

van*_*van 5

如果您想获取一本特定书籍的特定章节,下面的代码应该在一个 SQL 语句中完成:

book = ...  # get book instance 

chapter = (
    session.query(Chapter)
    .with_parent(book)
    .filter(Chapter.name == "57th Arabian Tale")
    .one()
)
Run Code Online (Sandbox Code Playgroud)

例如,如果您只有书名和章节标题,您可以这样做:

chapter = (
    session.query(Chapter)
    .join(Book)
    .filter(Book.name == "One Thousand and One Nights")
    .filter(Chapter.name == "57th Arabian Tale")
    .one()
)
Run Code Online (Sandbox Code Playgroud)

另请阅读使用联接进行查询以及SQLAlchemy 文档的其余部分。