Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Django automatically generate indexes for foreign keys columns?

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

like image 690
GabiMe Avatar asked May 12 '11 21:05

GabiMe


People also ask

Does foreign key create index automatically?

When you define a foreign key constraint in your database table, an index will not be created automatically on the foreign key columns, as in the PRIMARY KEY constraint situation in which a clustered index will be created automatically when defining it.

Are foreign key columns indexed?

MySQL requires that foreign key columns be indexed; if you create a table with a foreign key constraint but no index on a given column, an index is created. Information about foreign keys on InnoDB tables can also be found in the INNODB_FOREIGN and INNODB_FOREIGN_COLS tables, in the INFORMATION_SCHEMA database.

Do foreign keys get indexes?

Foreign keys do not create indexes. Only alternate key constraints(UNIQUE) and primary key constraints create indexes.


1 Answers

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.

like image 70
Luke Sneeringer Avatar answered Sep 24 '22 13:09

Luke Sneeringer