Reputation: 604
I'm working on a Django project using Postgresql as an attached database. I've noticed that some queries took a very long time and even found that I had over a dozen indexes on many different fields in my database, some that I've deemed unnecessary.
My plan is to remove the ones I do not need but I'm interested to know if Django does this in a "smart" way when creating models or there is some default mechanism in place for creating indexes that I am unaware of.
Upvotes: 11
Views: 7439
Reputation: 21807
Django does create indexes automatically for some fields. For example it is stated in the documentation for Foreign Keys:
A database index is automatically created on the ForeignKey. You can disable this by setting db_index to False.
Also when you set unique
to True
on a field:
Note that when unique is True, you don’t need to specify db_index, because unique implies the creation of an index.
Also on a SlugField
:
Implies setting Field.db_index to True.
On a field level you can control whether a field has an index or not by passing the db_index
argument to the field.
You can also specify the indexes
option in the models Meta
:
class MyModel(model.Model):
...
class Meta:
indexes = [
models.Index(fields=['field1', 'field2'], name='some_idx'),
]
Upvotes: 17