简体   繁体   English

优化Django:批量获取模型信息。

[英]Optimizing Django: getting model information in bulk..?

In a Django view I'm doing something like this.. 在Django视图中,我正在执行类似的操作。

lists = Stuff.objects.exclude(model2=None)
for alist in lists:                        
     if alist.model2.model3.id == target_id:
          addSomeStuff

The slowness comes from going from model (database row) to model in the if statement. 缓慢的原因是在if语句中从模型(数据库行)到模型。
This actually takes nearly a second to run when lists has only about 486 items in it. 当列表中只有大约486个项目时,实际上要花近一秒钟的时间。 I believe this is slow because 486*2+1 db lookups are being performed. 我认为这很慢,因为正在执行486 * 2 + 1 db查找。 If I where to rewrite this so it grabbed the whole model2 table and model3 table at once, and then just filter through there, it would be 3 db hits, I believe it would go much faster. 如果我在哪里重写它,以便它一次抓住了整个model2表和model3表,然后在那儿进行过滤,那将是3 db命中,我相信它将更快。 That would destroy all the niceness django makes though. 但这会破坏django的所有美感。

Is there any way to convince django to do some sort of bulk data lookup like this? 有什么办法说服django进行这样的批量数据查找?

Do

Stuff.objects.exclude(model2=None).select_related('model2')

and do 并做

if alist.model2.model3_id == target_id

These should cut it to just 1 SQL query. 这些应将其削减为仅1个SQL查询。

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

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