简体   繁体   English

为什么django ORM比原始SQL慢得多

[英]Why is django ORM so much slower than raw SQL

I have the following two pieces of code: 我有以下两段代码:

First, in SQL: 首先,在SQL中:

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

Next, in Django: 接下来,在Django中:

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

Doing it the first way is about 4x faster than the second way in a loop of 100k entries. 第一种方式是在100k条目的循环中比第二种方式快4倍。 What accounts for Django being so much slower? Django的速度如此之慢?

Typically ORMs go to the trouble of instantiating a complete object for each row and returning it. 通常,ORM会为每行实例化一个完整的对象并返回它而烦恼。 Your raw SQL doesn't do that, so it won't take the penalty that incurs. 您的原始SQL不会这样做,因此它不会受到引发的惩罚。 For large result sets where you don't intend to use the object, it is better to bypass the ORM. 对于不打算使用该对象的大型结果集,最好绕过ORM。

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

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