title: How to filter objects for count annotation in Django?
body: <p>Consider simple Django models <code>Event</code> and <code>Participant</code>:</p>
  <pre><code>class Event(models.Model):
      title = models.CharField(max_length=100)
  
  class Participant(models.Model):
      event = models.ForeignKey(Event, db_index=True)
      is_paid = models.BooleanField(default=False, db_index=True)
  </code></pre>
  <p>It's easy to annotate events query with total number of participants:</p>
  <pre><code>events = Event.objects.all().annotate(participants=models.Count('participant'))
  </code></pre>
  <p><strong>How to annotate with count of participants filtered by <code>is_paid=True</code>?</strong></p>
  <p>I need to query <strong>all events</strong> regardless of number of participants, e.g. I don't need to filter by annotated result. If there are <code>0</code> participants, that's ok, I just need <code>0</code> in annotated value.</p>
  <p>The <a href="https://docs.djangoproject.com/en/1.8/topics/db/aggregation/#order-of-annotate-and-filter-clauses" rel="nofollow noreferrer">example from documentation</a> doesn't work here, because it excludes objects from query instead of annotating them with <code>0</code>.</p>
  <p><strong>Update.</strong> Django 1.8 has new <a href="https://docs.djangoproject.com/en/1.8/ref/models/conditional-expressions/" rel="nofollow noreferrer">conditional expressions feature</a>, so now we can do like this:</p>
  <pre><code>events = Event.objects.all().annotate(paid_participants=models.Sum(
      models.Case(
          models.When(participant__is_paid=True, then=1),
          default=0,
          output_field=models.IntegerField()
      )))
  </code></pre>
  <p><strong>Update 2.</strong> Django 2.0 has new <a href="https://docs.djangoproject.com/en/2.0/ref/models/conditional-expressions/#conditional-aggregation" rel="nofollow noreferrer">Conditional aggregation</a> feature, see <a href="https://stackoverflow.com/a/48649024/326406">the accepted answer</a> below. This also works in Django 3.x</p>