title: How to generate indexes for related fields on Django models?
body: <p>Say we're building a Django-based site that clones Medium.com's URL structure, where you have users and articles. We'd probably have this model:</p>
  
  <pre><code>class Article(models.Model):
      user = models.ForeignKey(User)
      slug = models.CharField()
  </code></pre>
  
  <p>We want to be able to build URLs that look like <code>/&lt;username&gt;/&lt;slug&gt;/</code>. Since we're going to have billions of articles and zillions of pageviews, we want to put an index on that model:</p>
  
  <pre><code>class Meta:
      indexes = [
          models.Index(fields=['user__username', 'slug'])
      ]
  </code></pre>
  
  <p>But this causes the <code>makemigrations</code> command to fail with the following error:</p>
  
  <pre><code>django.core.exceptions.FieldDoesNotExist: Article has no field named 'user__username'. The app cache isn't ready yet, so if this is an auto-created related field, it won't be available yet.
  </code></pre>
  
  <p>So, plain vanilla <code>models.Index</code> doesn't support relational lookups like a QuerySet does. How would I add an index like this? Let's assume PostgreSQL, if that's helpful.</p>