114

Does Django automatically generate indexes for foreign keys, or does it just depend on the underlying DB policy ?

1
  • 2
    depend on db_index parameter in ForeignKey, which by default is True. Commented Jul 13, 2017 at 12:35

2 Answers 2

161

Django automatically creates an index for all models.ForeignKey columns.

From Django documentation:

A database index is automatically created on the ForeignKey. You can disable this by setting db_index to False. You may want to avoid the overhead of an index if you are creating a foreign key for consistency rather than joins, or if you will be creating an alternative index like a partial or multiple column index.

Sign up to request clarification or add additional context in comments.

8 Comments

Run ./manage.py sql appname and you'll see the SQL statements for the index creation. They come just after the SQL for the creation of the last table needed.
@LukeSneeringer, I'm not sure if the command you give used to show indices, but it no longer does. Instead, run ./manage.py sqlindexes appname for the indices by themselves.
It is also possible to disable creation of an index on a ForeignKey: code.djangoproject.com/ticket/13730
@JesseBeder: that ./manage.py sqlindexes appname doesn't work any longer in recent Django versions.
manage.py sqlindexes was removed in django 1.9 as shown here: docs.djangoproject.com/en/dev/internals/deprecation. In SQL, you can use SHOW INDEX FROM yourtable;, ref: stackoverflow.com/questions/5213339/…
|
2

In interest of visibility and the discussion going on in the comments of the accepted answer, adding it here.

  1. Yes, django automatically adds index for FK relationships.
  2. You can disable this by passing db_index=False like
models.ForeignKey(User, on_delete=models.CASCADE, db_index=False)
  1. This behavior depends on attached database -- (postgres/my-sql/oracle variants can have different SQL commands that are executed by django. MySQL creates such indexes automatically so django won't do that.)
  2. To verify what command is running for you: run
 ./manage.py sqlmigrate <app-name> <migration-number>

like

 ./manage.py sqlmigrate posts 0005

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.