title: Django inner join on self. Is there a more efficient approach?
body: <p>I have a model to track followers. This is a similar idea to every other social network site out there.</p>
  
  <p>Right now my model looks like this.</p>
  
  <pre><code>class Follow(models.Model):
      follower = models.ForeignKey(UserProfile, related_name='follower')
      following = models.ForeignKey(UserProfile, related_name='following')
      follow_date = models.DateTimeField(auto_now_add=True)
  </code></pre>
  
  <p>Today I went to add some functionality that requires a mutual relationship. Person a follows b and b follows a. I wanted the current logged in user included as well so I used Q.</p>
  
  <pre><code>mutual_follows_qs = Follow.objects.raw('select o.* from follow o ' + \
                                         'inner join follow f ' + \
                                         'on o.following_id = f.follower_id' + \
                                         ' and o.follower_id = f.following_id' + \
                                         ' where o.follower_id = %s', [str(request.user.pk)])
  mutual_follows = []
  for mutual_follow in mutual_follows_qs:
      mutual_follows.append(mutual_follow.following.pk)
  possible_users = User.objects.filter(Q(pk__in=mutual_follows) \
                                        | Q(pk=request.user.pk)).order_by('username')
  </code></pre>
  
  <p>I am executing more than one query. Yuck. I am building a list from my raw to use in <code>Q(pk__in=mutual_follows)</code>. Yuck. I am curious what suggestions people have to improve the efficiency of this logic.</p>
  
  <p>Here is the <code>UserProfile</code> model</p>
  
  <pre><code>class UserProfile(models.Model):
      user = models.OneToOneField(User)
      ...
      follow = models.ManyToManyField('self', blank = True, 
                                      symmetrical=False, through='Follow')
      ...
  </code></pre>