python - 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
)。
解决方案
鉴于您只对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
.
推荐阅读
- php - 图像未在服务器上使用 TCPDF 显示
- sql - SQlite3 Join 和多重排序
- reactjs - 如何删除/更新表格?
- mysql - 如何识别 MySQL 查询的非线性时间增加?
- android - 是否有任何 React Native 包可以帮助在 iOS 中实现新的面具解锁功能?
- python - Excel:如何在包含字符串的列中查找单元格并返回另一列行中单元格的值?
- python - 努力使用python代码按时间顺序对月度数据均值进行排序
- unix - 在 GitHub 工作流程中使用 Base64 图像编译 Latex 文件
- git - git push -u origin master 后没有结果
- google-chrome - android web 视图安全性