88

I'm reading a book about coding style in Django and one thing they discuss is db_index=True. Ever since I started using Django, I've never used this function because I'm not really sure what it does.

So my question is, when to consider adding indexes?

Zach Valenta
  • 1,783
  • 1
  • 20
  • 35
catherine
  • 22,492
  • 12
  • 61
  • 85

2 Answers2

172

This is not really django specific; more to do with databases. You add indexes on columns when you want to speed up searches on that column.

Typically, only the primary key is indexed by the database. This means look ups using the primary key are optimized.

If you do a lot of lookups on a secondary column, consider adding an index to that column to speed things up.

Keep in mind, like most problems of scale, these only apply if you have a statistically large number of rows (10,000 is not large).

Additionally, every time you do an insert, indexes need to be updated. So be careful on which column you add indexes.

As always, you can only optimize what you can measure - so use the EXPLAIN statement and your database logs (especially any slow query logs) to find out where indexes can be useful.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • 7
    this may help (a lot) https://github.com/django-debug-toolbar/django-debug-toolbar#django-debug-toolbar – maazza Jan 02 '14 at 09:04
  • 1
    Indexes can also speed up sorting. [This article](http://sqlmag.com/database-performance-tuning/indexing-sort-performance) is about MS SQL Server but the same goes for any database. – Nic Apr 11 '17 at 05:35
0

The above answer is correct but in some cases where the search is being done on columns that have only varchar datatype like email. There you need to add an index.

Following is the way of doing that:

Index(name='covering_index', fields=['headline'], include=['pub_date'])

reference from https://docs.djangoproject.com/en/3.2/ref/models/indexes/

Mohit Rathod
  • 1,057
  • 1
  • 19
  • 33