Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Indexes (db_index=True)

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?

like image 565
catherine Avatar asked Feb 09 '13 08:02

catherine


People also ask

What is db_index true in Django?

db_index. If True , a database index will be created for this field.

Does Django create indexes automatically?

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.

What is indexing in a database?

Indexes are used to quickly locate data without having to search every row in a database table every time a database table is accessed. Indexes can be created using one or more columns of a database table, providing the basis for both rapid random lookups and efficient access of ordered records.


1 Answers

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.

like image 72
Burhan Khalid Avatar answered Sep 28 '22 17:09

Burhan Khalid