django - Django 多重注释减慢查询速度
问题描述
我一直在调试django debug_toolbar
,如果我在查询中使用多个注释,那么 Django 获取查询结果需要很长时间。
class Project_First(models.Model):
project_first_results_M2M = models.ManyToManyField(Project_First_Results)
class Project_Second(models.Model):
project_second_results_M2M = models.ManyToManyField(Project_Second_Results)
class Project(models.Model):
project_first_M2M = models.ManyToManyField(Project_First)
project_second_M2M = models.ManyToManyField(Project_Second)
- 我正在尝试计算所有对象中存在
project_first_results_M2M
的所有project_first_M2M
对象。
即,假设project_first_M2M
有 3 个对象,Project_First
我想计算所有project_first_results_M2M
3 个对象中存在的所有对象。
Project.objects.all().annotate(first_res_count=Count('project_first_M2M__project_first_results_M2M',distinct=True))
- 上面的查询工作正常,需要 80 毫秒才能获取结果。但是当我尝试向
annotate
查询添加附加信息时会出现问题。
Project.objects.all().annotate(first_res_count=Count('project_first_M2M__project_first_results_M2M',distinct=True)).annotate(second_res_count=Count('project_second_M2M__project_second_results_M2M',distinct=True))
- 这将花费近 4000 毫秒来获取结果。
两者都project_second_M2M
包含project_first_M2M
相同的字段和相同数量的对象。我什至在反之亦然的情况下尝试了上述查询,并且只有当我添加额外annotate
的 .
- 是否有任何快速和替代的解决方案可以以更有效的方式实现相同的目标?也许使用原始 sql 查询。
- 我想计算每个对象内所有对象
project_first_results_M2M
的所有对象,类似地project_first_M2M
Project
project_second_results_M2M
解决方案
可能你可以使用prefetch related
:
Project.objects.prefetch_related('project_first_M2M__project_first_results_M2M', 'project_second_M2M__project_second_results_M2M').annotate(first_res_count=Count('project_first_M2M__project_first_results_M2M',distinct=True)).annotate(second_res_count=Count('project_second_M2M__project_second_results_M2M',distinct=True))
推荐阅读
- c# - 仅生成路径的 SVG 剪辑
- javafx - 如何完全重置表格视图以在同一个表格视图中显示不同结构的数据?
- powershell - 我如何在 Powershell 中查询新映像的 PC,然后给我最后一次登录的所有人的姓名
- sql - 在 Oracle 函数中使用变量
- tabulator - 如何为可移动行设置条件
- android - 通过firebase auth登录谷歌时出现错误
- database - 如果我有大量坐标列表,如何提取与特定 x 值对应的 y 值?
- javascript - 角色层次映射器/生成器(递归)
- javascript - 用 node js 执行命令行
- windows-installer - 在 StartService 操作期间摆脱错误消息框