我遇到了一些代码问题而我相信这是因为查询集的费用。我正在寻找一种便宜得多(就时间而言)的方式......
log.info("Getting Users")
employees = Employee.objects.filter(is_active = True)
log.info("Have Users")
if opt.supervisor:
if opt.hierarchical:
people = getSubs(employees, " ".join(args))
else:
people = employees.filter(supervisor__name__icontains = " ".join(args))
else:
log.info("Filtering Users")
people = employees.filter(name__icontains = " ".join(args)) | \
employees.filter(unix_accounts__username__icontains = " ".join(args))
log.info("Filtered Users")
log.info("Processing data")
np = []
for person in people:
unix, p4, bugz = "No", "No", "No"
if len(person.unix_accounts.all()): unix = "Yes"
if len(person.perforce_accounts.all()): p4 = "Yes"
if len(person.bugzilla_accounts.all()): bugz = "Yes"
if person.cell_phone != "": exphone = fixphone(person.cell_phone)
elif person.other_phone != "": exphone = fixphone(person.other_phone)
else: exphone = ""
np.append({ 'name':person.name,
'office_phone': fixphone(person.office_phone),
'position': person.position,
'location': person.location.description,
'email': person.email,
'functional_area': person.functional_area.name,
'department': person.department.name,
'supervisor': person.supervisor.name,
'unix': unix, 'perforce': p4, 'bugzilla':bugz,
'cell_phone': fixphone(exphone),
'fax': fixphone(person.fax),
'last_update': person.last_update.ctime() })
log.info("Have data")
现在这会生成一个看起来像这样的日志。
19:00:55 INFO phone phone Getting Users
19:00:57 INFO phone phone Have Users
19:00:57 INFO phone phone Processing data
19:01:30 INFO phone phone Have data
正如您所看到的,简单地迭代数据需要30秒以上。这太贵了。有人可以让我更有效地做到这一点。我想如果我做了第一个过滤器会让事情变得更容易,但似乎没有效果。我对此感到茫然。
由于
要明确这是大约1500名员工 - 不是太多!!
答案 0 :(得分:3)
Q
个对象代替QuerySet
s。QuerySet.select_related()
QuerySet.iterator()
QuerySet.extra()
添加IS NULL
字段,而不是循环中的三个len()
调用。