为什么django ORM比原始SQL慢得多 [英] Why is django ORM so much slower than raw SQL

查看:629
本文介绍了为什么django ORM比原始SQL慢得多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两段代码:

首先,在SQL中:

self.cursor.execute('SELECT apple_id FROM main_catalog WHERE apple_id=%s', apple_id)
if self.cursor.fetchone():
    print '##' 

接下来,在Django中:

Next, in Django:

if Catalog.objects.filter(apple_id=apple_id).exists():
    print '>>>'

第一种方式比100k条目循环中的第二种方法快约4倍。对于Django来说,这么慢呢?

Doing it the first way is about 4x faster than the second way in a loop of 100k entries. What accounts for Django being so much slower?

推荐答案

通常情况下,ORM会为每一行实例化一个完整的对象而返回它。您的原始SQL不会这样做,所以不会受到招致的惩罚。对于不想使用对象的大型结果集,最好绕过ORM。

Typically ORMs go to the trouble of instantiating a complete object for each row and returning it. Your raw SQL doesn't do that, so it won't take the penalty that incurs. For large result sets where you don't intend to use the object, it is better to bypass the ORM.

这篇关于为什么django ORM比原始SQL慢得多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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