- we have
Project
as main model, which contains 2 fields of M2M relationship.
class First(models.Model):
first_results_M2M = models.ManyToManyField(First_Results)
class Second(models.Model):
second_results_M2M = models.ManyToManyField(Second_Results)
class Project(models.Model):
project_first_M2M = models.ManyToManyField(First)
project_second_M2M = models.ManyToManyField(Second)
I m trying to count all the objects present in
first_results_M2M
of all theproject_first_M2M
objects within eachProject
object.Here's the below example to count all the objects of
first_results_M2M
forProject
object 1.
total_first_all = First_Results.objects.filter(first__project__id=1).count()
- I want to render the total count of
total_first_all
andtotal_second_all
in the template.
Project_Query = Project.objects.all()
for each_proj in Project_Query:
print(each_proj.total_first_all) ## should print the count the `first_resuls_M2M` for each project obj.
- Please let me know how to do achieve it in more effecient/fast way besides annotate.
annotate.total_first_all=Count('project_first_M2M__first_results_M2M')