[Django]-Django filter the model on ManyToMany count?

152πŸ‘

βœ…

If this works this is how I would do it.

Best way can mean a lot of things: best performance, most maintainable, etc. Therefore I will not say this is the best way, but I like to stick to the ORM features as much as possible since it seems more maintainable.

from django.db.models import Count

user = Hipster.objects.get(pk=1) 
hip_parties = (Party.objects.annotate(num_participants=Count('participants'))
                            .filter(organiser=user, num_participants__gt=0))
πŸ‘€solartic

37πŸ‘

Party.objects.filter(organizer=user, participants__isnull=False)
Party.objects.filter(organizer=user, participants=None)

6πŸ‘

Easier with exclude:

# organized by user and has more than 0 participants
Party.objects.filter(organizer=user).exclude(participants=None)

Also returns distinct results

5πŸ‘

Derived from @Yuji-β€˜Tomita’-Tomita answer, I’ve also added .distinct(β€˜id’) to exclude the duplitate records:

Party.objects.filter(organizer=user, participants__isnull=False).distinct('id')

Therefore, each party is listed only once.

πŸ‘€Kostyantyn

0πŸ‘

I use the following method when trying to return a queryset having at least one object in a manytomany field:
First, return all the possible manytomany objects:

profiles = Profile.objects.all()

Next, filter the model by returning only the queryset containing at least one of the profiles:

hid_parties = Party.objects.filter(profiles__in=profiles)

To do the above in a single line:

hid_parties = Party.objects.filter(profiles__in=Profile.objects.all())

You can further refine individual querysets the normal way for more specific filtering.
NOTE:This may not be the most effective way, but at least it works for me.

πŸ‘€George Oyosa

Leave a comment