[Answered ]-How to get Count of objects by aggregate within Queryset class

1👍

Likely the easiest way to obtain the Chatroom with the largest number of members is with:

from django.db.models import Count

Chatroom.objects.annotate(
    nmembers=Count('members')
).order_by('-nmembers').first()

Since , you can work with .alias(…) [Django-doc] to prevent calculating the number of members twice:

from django.db.models import Count

Chatroom.objects.alias(
    nmembers=Count('members')
).order_by('-nmembers').first()

Leave a comment