简体   繁体   English

在SQLAlchemy中,.first()和[0]之间的性能有何不同?

[英]In SQLAlchemy, any performance difference between .first() and [0]?

Any difference between 之间的任何区别

a = session.query(Accounts).filter(Accounts.key = 4).first()

and

a = session.query(Accounts).filter(Accounts.key = 4)[0]

?

apparently, there isn't much difference between useing __gettitem__ or first 显然,使用__gettitem__first并没有太大区别

hint: both of the above calls basically return the same as: 提示:以上两个调用基本上都返回相同的内容:

query = session.query(Accounts).filter(Accounts.key = 4)
a = list(query[0:1])[0]

As @mata indicated and pointed to the source code, there is no difference in the execution path of the two. 正如@mata指出并指向源代码一样,两者的执行路径没有区别。 In fact, you can also enable SQL logging by setting echo=True when you create an engine, and you will see that the both SQL statements are exactly the same (some sort of SELECT ... FROM ... WHERE ....id = ? LIMIT ? OFFSET ? ) 实际上,您还可以在创建引擎时通过设置echo=True来启用SQL日志记录,并且您会看到两个SQL语句完全相同(某种SELECT ... FROM ... WHERE ....id = ? LIMIT ? OFFSET ?

But, if the Accounts.key is actually a primary key, the best way to get a persistent instance by the primary key is to use the Query.get method, which will generate SELECT ... FROM ... WHERE ....id = ? 但是,如果Accounts.key实际上是主键,则通过主键获取持久实例的最佳方法是使用Query.get方法,该方法将生成SELECT ... FROM ... WHERE ....id = ? and it should be good enough. 而且应该足够好了 I assume it is not going to be faster, but is much cleaner. 我认为它不会更快,但是更干净。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM