假设我有以下内容(在python3和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
这感觉像是一种“非惯用”方法,因为它似乎不太可能利用数据库来搜索给定章节。在最坏的情况下,似乎是n
调用db来检查章节标题,尽管我对SQLAlchemy的理解有限,这表明可以对其进行配置。如果你不知道一个查询对象的方法是什么?如果是这样的话,怎么做呢?在
如果您想获取特定书籍的特定章节,请使用以下代码在一条SQL语句中完成:
例如,如果您只有书名和章节标题,您可以这样做:
^{pr2}$还要读Querying with Joins和SQLAlchemy Documentation的其余部分。
相关问题 更多 >
编程相关推荐