我一直在调试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))
Both project_second_M2M
and project_first_M2M
包含相同的字段和相同数量的对象。我什至尝试在反之亦然的情况下对上述查询进行操作,并且仅当我添加额外的查询时查询才会减慢annotate
.
- 是否有任何快速且替代的解决方案可以以更有效的方式实现相同的目标?也许使用原始 sql 查询。
- 我想计算所有的对象
project_first_results_M2M
of all project_first_M2M
每个内的对象Project
对象,类似地project_second_results_M2M
也许你可以使用prefetch related https://docs.djangoproject.com/en/3.0/ref/models/querysets/#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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)