Django filtering model on ManyToMany account?

Suppose I have something like this in my models.py:

class Hipster(models.Model): name = CharField(max_length=50) class Party(models.Model): organiser = models.ForeignKey() participants = models.ManyToManyField(Profile, related_name="participants") 

Now in my view.py I would like to make a request that will receive a batch for a user with more than 0 members.

Something like this could be:

 user = Hipster.get(pk=1) hip_parties = Party.objects.filter(organiser=user, len(participants) > 0) 

What is the best way to do this?

+50
django django-models django-queryset
Oct 25 '11 at 2:01
source share
3 answers

If so, I will do it.

A better way can mean many things: better performance, most supported, etc. Therefore, I will not say that this is the best way, but I like to stick to the ORM functions as much as possible, since it seems more convenient.

 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)) 
+90
Oct 25 '11 at 2:28
source share
 Party.objects.filter(organizer=user, participants__isnull=False) Party.objects.filter(organizer=user, participants=None) 
+28
Oct 25 '11 at 5:11
source share

Easier with exclude :

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

Also returns great results.

+3
Jul 08 '16 at 17:18
source share



All Articles