11

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.

1 Answer 1

17

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'),
        ]
Sign up to request clarification or add additional context in comments.

4 Comments

Is it best practice to have an index for each foreign key in my database?
@ThatcherThornberry that totally depends on your need. If you see the documentation on Foreign Keys that I have linked it also states that "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."
is this meta option will create indexing on individual fields or joint index ?
@DeepanshuMehta there will be an index created for each instance of Index in the list indexes. So for the given example it creates one multi-column index on the fields 'field1' and 'field2'. You can read the linked documentation (which also further links to Model index reference) for more info.

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.