首页 > 解决方案 > Django - 惰性查询和效率

问题描述

有没有办法加快这个速度?

section_list_active = Section.objects.all().filter(course=this_course,Active=True,filter(teacher__in=[this_teacher]).order_by('pk')
if section_list_active.count() > 0:
    active_section_id = section_list_active.first().pk
else:
    section_list = Section.objects.all().filter(course=this_course).filter(teacher__in=[this_teacher]).order_by('pk')
    active_section_id = section_list.first().pk

我知道查询集在使用之前不会被评估(.first().pk位?),那么有没有更快的方法来做到这一点?如果他们不懒惰,我可以为整个部分列表点击数据库,然后只为具有属性的部分过滤该设置Active,但我不知道如何在不点击两次的情况下做到这一点(假设我有去else)。

标签: pythondjangodjango-queryset

解决方案


鉴于您只对Section(或相应的pk)感兴趣,的。您可以先按Active字段排序:

active_section_id = Section.objects.filter(
    course=this_course,
    teacher=this_teacher
).order_by('-Active', 'pk').first().pk

甚至更优雅一点:

active_section_id = Section.objects.filter(
    course=this_course,
    teacher=this_teacher
).earliest('-Active', 'pk').pk

因此,我们将首先按Active降序排列,这样如果有一行带有Active=True,那么这一行将排在顶部。接下来我们因此获取.first()对象,并可选地获取pk.

如果没有Section满足过滤条件的,则.first()or.earliest()将返回None,这将导致AttributeError获取pk属性时出现错误。

注意:通常字段以小写字母书写,因此active而不是Active.


推荐阅读