13

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?

3
  • Please have a look into the docs or google for annontations and aggregations with the ORM, should get you started.
    – Jingo
    Aug 23, 2012 at 23:48
  • 1
    I have done. I am looking for more specific advice. The standard filters given seem to filter according to specific attributes of a single related model object rather than a set of them. I suppose I am looking for information which seems a little more esoteric.
    – KindOfGuy
    Aug 23, 2012 at 23:52
  • Uha, looking at Yuji's advice below, I realised I hadn't looked into what you said. Thanks for the advice!
    – KindOfGuy
    Aug 24, 2012 at 0:04

1 Answer 1

18
Event.objects.annotate(c=Count('userprofile')).filter(c__lt=4)
1
  • 3
    Superb! I had to add from django.db.models import Count to models.py, of course, but this has worked. Yuji, you are a very strong and important citizen.
    – KindOfGuy
    Aug 24, 2012 at 0:09

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.