1

i want to get object that is Maximum length/count of ManyToMany Field

class Member(models.Model):
    pass

class Chatroom(models.Model):
    ...
    members = models.ManyToMany(Member)
    ...

chatRoom = Chatroom.objects.aggregate(Max('members'))
### {'members__max':15}

this code does not return an object like:class <QuerySet [object]> but i want to take an object to do something so i did do this

room = ChatRoom.objects.aggregate(max_value=Max('members')).get(members__count=max_value)

its got an Error : it says there is no __count look up.. could you help me please...

1
  • 1
    Do you simply want the ChatRoom with the most members? Note that Max('members') will not do what you assume it does, it will only give the maximum id of the Member table. Commented Jun 12, 2021 at 8:16

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.