2👍
Probably you can use 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))
0👍
If you annotate on multiple different joins you generate a large amount of JOINs (in that example a total of four), which will indeed “blow up”, the solution table. But it of course does not make any sense to perform such query. If you here perform a single nested JOIN, then it results in two JOINs, and you take all records that are yielded into account. – Williem
The solution proposed by Matthew Schinckel
at Django 1.11 Annotating a Subquery Aggregate using subquery trick for results in a much faster and optimized way.
- [Django]-Django Tables adding a LinkColumn / NoReverseMatch Error
- [Django]-Django for a simple web application
- [Django]-Easy way to exclude django _state attribute from jsonpickle.encode
Source:stackexchange.com