Django-惰性查询和效率

时间:2018-08-13 18:39:59

标签: python django django-queryset

有没有办法加快速度?

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)。

1 个答案:

答案 0 :(得分:0)

鉴于您只对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().earliest()将返回None,因此将导致{{1} }时提取AttributeError属性。

  

注意:通常,字段以小写书写,因此pk而非active

相关问题