Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query filter by number of ManyToMany objects

I have two models (Event and UserProfile) in a ManyToMany relation. I want to select just those Events that have less than a certain number of Users associated with them. So events where less than 4 people have so far signed up should be selected.

In views.py I have something like this but it is not working:

proposed_event_list = Event.objects.all().filter(userprofile__lt=4)

The relevant parts of models.py look like:

class Event(models.Model):
    name = models.CharField(max_length=100)
    date = models.DateTimeField('Event date')

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    event_commitments = models.ManyToManyField(Event, null=True, blank=True)

I guess I'm not correctly filtering with all Userprofiles on each event, but I don't know how to do it.

Can you help?

like image 360
KindOfGuy Avatar asked Aug 23 '12 23:08

KindOfGuy


1 Answers

Event.objects.annotate(c=Count('userprofile')).filter(c__lt=4)
like image 151
Yuji 'Tomita' Tomita Avatar answered Oct 23 '22 09:10

Yuji 'Tomita' Tomita