Can anybody explain db_index and index_together means and how it works? I tried to look on django documentations but there is no enough explanation about db_index when it sets to True, and also about index_together. Some says that it helps with the efficiency in look ups, so how do I use it? and what’s the proper way of implementing it. Are these two different from each other? Thank you!
Say I have a model which has first_name
and last_name
. Say I wish to index on just the first_name
, then one could pass in the arg db_index=True
to make that column an index. This helps the DB find entries quickly via this value.
e.g.
first_name = models.CharField(db_index=True)
However say now you wish to index on the combination of the first_name
and the last_name
. db_index
= True
sets an index for that column column only. However now we wish to index the combination of two fields.
e.g.
class Meta:
indexes = (
models.Index(fields=('first_name', 'last_name')),
)
This tells the DB to make a single index, and the values of the index is the first_name
+ last_name
.
Side note: Foreigns automatically are indexed by default.
You (as the application author), don’t use indexes. The database engine, based upon the results of the query planner, decides whether or not to use an index in any particular query.
In many cases, the addition of proper indexes may reduce the time required for a SELECT. However, adding indexes increases the amount of time required for an INSERT, UPDATE, or DELETE.