Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>>> 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')
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading