Ronen Ness
Ronen Ness

Reputation: 10740

django db_index for foreign key reverse lookup

I've read that django creates db_index automatically for all foreign keys. However, does that db_index improve the performance of the reverse lookup as well?

For example, if B has a foreign key to A and I use a.b_set.all(), do I enjoy the performance boost from the db index or not?

And if not, is there a way to make the foreign key reverse lookup faster with db index?

Thanks,

Upvotes: 8

Views: 1634

Answers (1)

Todor
Todor

Reputation: 16010

Let's say the you have a simple model structure:

class Author(models.Model):
    name = models.CharField(max_length=70)
    email = models.EmailField()

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author)

As you mention Book.author already have index, because it's a ForeignKey

Now querying:

author_books = Book.objects.filter(author=a)

or

author_books = a.book_set.all()

produce the exact same query, therefore the book.author index will be used in both situations.

Upvotes: 7

Related Questions