首页 > 解决方案 > 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_M2M有 3 个对象,Project_First我想计算所有project_first_results_M2M3 个对象中存在的所有对象。

Project.objects.all().annotate(first_res_count=Count('project_first_M2M__project_first_results_M2M',distinct=True))
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))

两者都project_second_M2M包含project_first_M2M相同的字段和相同数量的对象。我什至在反之亦然的情况下尝试了上述查询,并且只有当我添加额外annotate的 .

标签: djangodjango-modelsdjango-rest-frameworkdjango-formsdjango-templates

解决方案


可能你可以使用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))

推荐阅读