aemdy
aemdy

Reputation: 3802

Counting M2M objects in Django

I have the following model:

class Task(Model):

solvers = ManyToManyField(User, related_name='slvrs')

Now I want to count the total number of solvers of all the tasks. For example there are 3 Task objects in the database. The first one has been solved by 2 users (M2M field relates to 2 users), the second by 3 and the last one by 0. I should get the count of all these solvers: 2 + 3 + 0 = 5.

I believe I have to use Count aggregate, but I have know idea on which models and which annotations.

Upvotes: 0

Views: 266

Answers (1)

Task.objects.aggregate(count=Count('solvers'))['count']

Should get you what you need.

Upvotes: 1

Related Questions