1

I am using annotate on a django queryset:

class MyModel(models.Model):
   my_m2m = models.ManytoManyField()

my_qs = MyModel.objects.all().annotate(total_m2m=Count('my_m2m'))

This yields the desired result. E.g:

>>> my_qs[0].total_m2m
>>> 3

How do I use aggregate to count the total number of my_m2m in the queryset? E.g.

>>> my_qs.aggregate_m2m
>>> 9
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
alias51
  • 8,178
  • 22
  • 94
  • 166

1 Answers1

1

You can sum up, so:

from django.db.models import Count, Sum


MyModel.objects.annotate(total_m2m=Count('my_m2m')).aggregate(
    total=Sum('total_m2m')
)

but here it makes more sense to aggregate immediately:

from django.db.models import Count


MyModel.objects.aggregate(
    total=Count('my_m2m')
)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555