Search code examples
pythondjangopostgresqldjango-modelsdjango-annotate

Is it possible to use aggregate on a queryset annotation?


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

Solution

  • 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')
    )