title: Optimise Django subquery (currently using `annotate` and `Count`)
body: <p><strong>Using:</strong> Django 1.11, Postgres 9.6</p>
  
  <p>I need to optimise a Django ORM query for consumption by the Django Rest Framework. The query must return records that:</p>
  
  <ol>
  <li>Match a list of IDs in their <code>target</code> field</li>
  <li>Limit the result set to records where a <code>source</code> ID appears more than once in the set.</li>
  </ol>
  
  <p>The current approach is to create a subquery using <code>annotate</code> and <code>Count</code> but the sheer amount of processing behind each request added to pagination means that the apps that it's causing timeouts or very slow behaviour.</p>
  
  <p>If there is anything that can be done by Postgres on the server as a raw query I'm fine with that.</p>
  
  <p><strong>Model:</strong></p>
  
  <pre><code>class Relationship(models.Model):
      id = models.AutoField(primary_key=True)
      source = models.BigIntegerField(db_index=True)
      target = models.BigIntegerField(db_index=True)
  </code></pre>
  
  <p><strong>View snippet:</strong></p>
  
  <pre><code>match_list = [123, 456, 789] # dummy data for example
  queryset = Relationship.objects.filter(target__in=match_list)
  sub_queryset = (Relationship.objects.filter(target__in=_match_list)
                                      .values('source')
                                      .annotate(source_count=Count("source"))
                                      .filter(source_count__gt=1)
                                      )
  sub_ids = [i["source"] for i in sub_queryset]
  queryset = (queryset.filter(source__in=sub_ids)
              )
  </code></pre>
  
  <p>The API takes a list of target IDs as an argument and responds with a list of all <code>source</code> IDs that are connected to that target. However, I'm filtering the queryset to only return <code>source</code> records that are connected to two or more <code>target</code>s.</p>
  
  <p>As background, the resulting queryset will be served by Django Rest Framework and it's currently causing timeouts because the requests get exponentially longer the more </p>
  
  <p><strong><em>Note</strong>: I'm putting this on SO because it's causing my requests to timeout and therefore causing a fault. I know I could extend the timeout duration but would rather optimise the query. I considered CodeReview but felt this was more appropriate.</em></p>
  
  <p><strong>Edit 1</strong>: Following <code>@albar</code>'s suggestion, it's currently a separate subquery as the <code>annotate</code> / <code>Count</code> operation only works if the values are returned, not full records</p>