Does Django automatically generate indexes for foreign keys, or does it just depend on the underlying DB policy ?
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.
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.
Foreign keys do not create indexes. Only alternate key constraints(UNIQUE) and primary key constraints create indexes.
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 settingdb_index
toFalse
. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With