As I've just start learning to use sqlalchemy recently, the result of the following code make me confused about when sqlalchemy execute the query:
由于我刚开始学习使用sqlalchemy,以下代码的结果让我对sqlalchemy执行查询时感到困惑:
query = db.session.query(MyTable)
query = query.filter(...)
query = query.limit(...)
query = query.offset(...)
records = query #records=query.all()
for r in records:
#do something
note the line
注意这条线
records = query #records=query.all()
Seems that it brings the same correct result(stored in variable "records") when using "query" and "query.all()", I wonder when was the query executed?
当使用“query”和“query.all()”时,它似乎带来了相同的正确结果(存储在变量“records”中),我想知道查询是什么时候执行的?
If it is executed during the first line "db.session.query(MyTable)", the result set may be large at this point; if during the fifth line "records = query", how could that happen as there's no function call at all?
如果它在第一行“db.session.query(MyTable)”期间执行,则此时结果集可能很大;如果在第五行“记录=查询”期间,那怎么可能发生,因为根本没有函数调用?
1 个解决方案
#1
In your example, the query gets executed upon for r in records
. Accessing the query object via iterator triggers the execution. (Normally, only then will it be compiled into a SELECT
statement)
在您的示例中,对记录中的r执行查询。通过迭代器访问查询对象会触发执行。 (通常,只有这样才能编译成SELECT语句)
Up until this time, the query will be built (via filter
, limit
etc).
在此之前,将构建查询(通过过滤器,限制等)。
Please read also the ORM Tutorial on querying
请阅读有关查询的ORM教程
#1
In your example, the query gets executed upon for r in records
. Accessing the query object via iterator triggers the execution. (Normally, only then will it be compiled into a SELECT
statement)
在您的示例中,对记录中的r执行查询。通过迭代器访问查询对象会触发执行。 (通常,只有这样才能编译成SELECT语句)
Up until this time, the query will be built (via filter
, limit
etc).
在此之前,将构建查询(通过过滤器,限制等)。
Please read also the ORM Tutorial on querying
请阅读有关查询的ORM教程