在使用Django QuerySets时,使用list comprehension而不是for循环 [英] Using list comprehension instead of for loop when working with Django QuerySets

查看:541
本文介绍了在使用Django QuerySets时,使用list comprehension而不是for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调整在速度部门遇到的应用程序。因此,我已经开始将所有的for-loop语句转换成list可能的列表。



目前,我正在开发一个需要迭代的函数Django querysets的字典。旧的代码使用for-loop语句来遍历这个,它的工作正常。我的代码使用list comprehension返回django查询而不是我的模型对象。



这是代码:

  def get_children(parent):
#以下工作
children = []
在get_data_map(父)中的值.itervalues():
children + = list(value)
#这部分不按预期工作。
booms = [get_data_map(parent)中的值的值.itervalues()if value]
import pdb
pdb.set_trace()


Pdb)type(children [0])
< class'site.myapp.models.Children'>

(Pdb)类型(booms [0])
< class'django.db.models.query.QuerySet'>

请注意,get_data_map返回值为< class'django的字典。 db.models.query.QuerySet'>



这部分代码是应用程序中最耗时的部分之一。如果我在列表推导中得到这个工作,那么应用速度将有望更快地提高两倍。



任何想法如何加速这部分代码? p>

解决方案

您的问题不是 for loops vs. list comprehensions是发电机)。您的问题是对数据库的查询太多。



由于您正在尝试获取一个列表,您应该尝试获取从一个查询。如果您解释了典型的QuerySet中的内容,我们可以告诉您如何最佳地合并它们。也许使用 OR 在Q对象上合并。或者可能建立一组整数,并将其提供给 __ in = 过滤器。


I'm trying to tweak an application that is suffering in speed department. Because of that, I've started converting all the for-loop statements to list comprehensions when possible.

Currently, I'm working on a function that needs to iterate through a dictionary of Django querysets. The old code uses for-loop statement to iterate through this and it works fine. My code that uses list comprehension returns django querysets instead of my model object.

Here is the code:

def get_children(parent):
  # The following works
  children = []
  for value in get_data_map(parent).itervalues():
    children += list(value)
  # This part doesn't work as intended.
  booms = [value for value in get_data_map(parent).itervalues() if value]
  import pdb
  pdb.set_trace()


(Pdb) type(children[0])
<class 'site.myapp.models.Children'>

(Pdb) type(booms[0])
<class 'django.db.models.query.QuerySet'>

Note that get_data_map returns a dictionary whose values are <class 'django.db.models.query.QuerySet'>

This part of code is one of the most time consuming part of the application. If I get this working on list comprehensions, the application speed will hopefully get faster by two times.

Any idea how I can speed up this part of the code?

解决方案

Your problem isn't for loops vs. list comprehensions (better would be generators). Your problem is way too many queries to the database.

Since you're trying to get one list, you should be trying to get it from one query. If you explained what was in your typical QuerySet, we could show you how best to merge them. Maybe use OR merges on Q objects. Or maybe building up a set of integers and feeding it to an __in= filter.

这篇关于在使用Django QuerySets时,使用list comprehension而不是for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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