Count attributes of many to many relation and filter by it
Question: I would like to do something slightly different than
[this](http://stackoverflow.com/questions/7883916/django-filter-the-model-on-
manytomany-count).

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

    
    
    class Hipster(models.Model):
      name = CharField(max_length=50)
      has_iphone = BooleanField(default=True)
    
    class Party(models.Model):
      participants = models.ManyToManyField(Hipster, related_name="participants")
    

And then do:

    
    
    hip_parties = Party.objects.filter(participants__has_iphone__istrue__count=4)
    

How can I do that?

UPDATE:

    
    
    >>> Question.objects.filter(options__is_correct=True).annotate(options__count=Count('options')).filter(options__count=0)
    []
    >>> q = Question.objects.get(id=49835)
    >>> q.options.all()[0].is_correct
    False
    >>> q.options.all()[1].is_correct
    False
    >>> q.options.all()[2].is_correct
    False
    >>> q.options.all()[3].is_correct
    False
    >>> q.options.all()[4].is_correct
    False
    >>> q.options.all()[5].is_correct
    Traceback (most recent call last):
      File "<console>", line 1, in <module>
      File "/Users/patrickbassut/Programming/logus/lib/python2.7/site-packages/django/db/models/query.py", line 177, in __getitem__
        return list(qs)[0]
    IndexError: list index out of range
    


Answer: You can use annotations for this.

    
    
    from django.db.models import Count
    Party.objects.filter(
        participants__has_iphone=True
    ).annotate(iphone_count=Count('participants')).filter(
        iphone_count=4
    )
    

