SQL Alchemy查询何时实际对数据库进行查询?

3

我正在查看一些代码,它有条件地创建一个查询对象,然后查看查询结果。例如:

query = self.session.query(Person).filter(Person.last_name == "Jones") #line 1
#some other logic
query = query.filter(Person.title == "VP Sales") #line 3
#some other logic
query.first() #line 5

查询语句何时实际命中数据库?理想情况下,只有在需要使用查询结果时(例如第5行)才运行查询。

我尝试查看SQLAlchemy文档(https://docs.sqlalchemy.org/en/13/orm/query.html),但未能找到此信息。


2
尝试在文档中查找“lazy”,因为这是您正在寻找的术语。 - ipaleka
它无法在第1行运行,因为它不知道您是否会稍后添加更多过滤器。第3行也是如此;只有当您实际请求数据时,才断言查询已完成变异。 - Charles Duffy
1个回答

2
在这种情况下,在调用.first()时会命中数据库,其余行只是格式化查询对象。
话虽如此,当您迭代查询对象或调用.all()时,查询也会立即触发。
query = self.session.query(Person).filter(Person.last_name == "Jones") 
query = query.filter(Person.title == "VP Sales") #line 3

for person in query:    # hit db here
    print(peron)

# OR

persons = query.all()   # hit db here

# OR

persons = list(query)   # hit db here (note that this has the same effect as calling .all())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接