Django 1.11 offers new ways to create database indexes. So far we had db_index=True
in each field:
# example 1
class Person(models.Model):
name = models.CharField(db_index=True)
age = models.IntegerField(db_index=True)
Now we have models.Index
and the possibility of declaring indexes
within the class Meta
block — or even index_together
.
That said I have two doubts:
1. Is the code from example 1 doing the same thing as example 2 below?
# example 2
class Person(models.Model):
name = models.CharField()
age = models.IntegerField()
class Meta:
indexes = [
models.Index(fields=['name']),
models.Index(fields=['age'])
]
2. What about index
with multiple fields and index_together
: are examples 3 and 4 below doing exactly the same thing?
# example 3
class Person(models.Model):
name = models.CharField()
age = models.IntegerField()
class Meta:
indexes = [
models.Index(fields=['name', 'age'])
]
# example 4
class Person(models.Model):
name = models.CharField()
age = models.IntegerField()
class Meta:
index_together = [['name', 'age']]
What are the diferences between 1 and 2, and differences between 3 and 4? What am I missing? Many thanks.
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.
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.
To define an index with a descending order for a column, add a hyphen before the field's name. For your query, models. Index(fields=['last_name', 'first_name','-date_of_birth',]), would create SQL with (last_name, first_name, date_of_birth DESC).
According to the docs, you can give indexes a name and you can set an order for each field in the index (but not all DBs are equally supported). But in reality the whole point of this is to bring extra flexibility to define other types of indexes where supported.
Currently as of Django 1.11 and only when using Postgres you can define GIN and BRIN indexes if that is something that would fit your needs. (see django.contrib.postgres.indexes at https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/indexes/)
Being able to define indexes as you described is just the most general case and unless you want to use a feature named above (naming indexes or ordering fields) you can probably use indexes as you've been doing until now (db_index and index_together).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With