Sqlalchemy - for 循环中 query 和 query.all 的区别 [英] Sqlalchemy - Difference between query and query.all in for loops

查看:52
本文介绍了Sqlalchemy - for 循环中 query 和 query.all 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问一下有什么区别

for row in session.Query(Model1):
    pass

for row in session.Query(Model1).all():
    pass

是第一个以某种方式使用单个查询轰炸您的数据库的迭代器,而后者急切地"将整个事物作为列表查询(例如 range(x) 与 xrange(x))?

is the first somehow an iterator bombarding your DB with single queries and the latter "eager" queries the whole thing as a list (like range(x) vs xrange(x)) ?

推荐答案

不,DB 流量没有区别.不同之处仅在于 for row in session.Query(Model1) 在每行将要给你的时候做 ORM 工作,而 for row in session.Query(Model1)).all() 在开始将它们提供给您之前,对所有行进行 ORM 工作.

Nope, there is no difference in DB traffic. The difference is just that for row in session.Query(Model1) does the ORM work on each row when it is about to give it to you, while for row in session.Query(Model1).all() does the ORM work on all rows, before starting to give them to you.

请注意,q.all() 只是 list(q) 的糖,即将生成器生成的所有内容收集到列表中.这是它的源代码,在Query 类(在链接源中查找 def all):

Note that q.all() is just sugar for list(q), i.e. collecting everything yielded by the generator into a list. Here is the source code for it, in the Query class (find def all in the linked source):

def all(self):
    """Return the results represented by this ``Query`` as a list.

    This results in an execution of the underlying query.

    """
    return list(self)

... 其中查询对象 self 是一个可迭代对象,即有一个 __iter__ 方法.

... where self, the query object, is an iterable, i.e. has an __iter__ method.

所以从逻辑上讲,这两种方式在数据库流量方面完全相同;两者最终都调用 query.__iter__() 来获得一个行迭代器,然后 next() 通过它.

So logically the two ways are exactly the same in terms of DB traffic; both end up calling query.__iter__() to get a row iterator, and next()ing their way through it.

实际区别在于前者可以在数据到达后立即开始为您提供行,将数据库结果集流式传输"给您,从而减少内存使用和延迟.我不能确定所有当前的引擎实现都这样做(我希望他们这样做!).在任何情况下,后一个版本都无缘无故地阻碍了这种效率.

The practical difference is that the former can start giving you rows as soon as their data has arrived, "streaming" the DB result set to you, with less memory use and latency. I can't state for sure that all the current engine implementations do that (I hope they do!). In any case the latter version prevents that efficiency, for no good reason.

这篇关于Sqlalchemy - for 循环中 query 和 query.all 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆