Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 369
Ronen Ness Avatar asked Jul 01 '16 18:07

Ronen Ness


1 Answers

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.

like image 125
Todor Avatar answered Oct 24 '22 01:10

Todor