title: Django complex query filter through reverse relationships
body: <p>I have two models:</p>
  
  <pre><code>class User(AbstractBaseUser, PermissionsMixin):
      username = models.CharField(db_index=True, max_length=20, unique = True)
  
  class UserProfile(models.Model):
      user = models.OneToOneField(User, on_delete=models.CASCADE)
      full_name = models.CharField(db_index=True, max_length=256, null=True)
      friends = models.ManyToManyField("self", related_name = 'friends', symmetrical=True)
  </code></pre>
  
  <p>For search purposes, I need a query to:</p>
  
  <ol>
  <li><p>SELECT all friends and friends of friends (excluding self)</p></li>
  <li><p>WHERE username__startswith(<code>query</code>) OR full_name__startswith(<code>query</code>)</p></li>
  </ol>
  
  <p>I can't figure out how to do that given the structure: need to access friends, then friends of friends and reverse <code>User</code> objects. The question therefore is:
  <strong>Can I avoid looping through the results and apply a filter to make the database do the work?</strong></p>