When setting up models in Django, it is recommended to set an index for the specific fields of that Model.

Index is a performance-enhancing feature, that allows a database to quickly locate and retrieve specific data from a table.

It makes searching/sorting data in the database easier and more efficient.

Here are some reasons why you might want to set an index on a field in a Django model:

  1. To improve the performance of queries that filter or sort data based on the indexed field.
  2. To enforce uniqueness constraints on the field.
  3. To improve the performance of foreign key relationships by creating a link between the primary key of one table and the indexed field of another table.

Index class is located in the Meta inner class of your model.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Order(models.Model):

	first_name = models.CharField(max_length=50)
	last_name = models.CharField(max_length=50)
	email = models.EmailField()
	address = models.CharField(max_length=250)
	postal_code = models.CharField(max_length=20)
	city = models.CharField(max_length=100)
	created = models.DateTimeField(auto_now_add=True)
	updated = models.DateTimeField(auto_now=True)
	paid = models.BooleanField(default=False)

	class Meta:

		ordering = ['-created']
		indexes = [
			models.Index(fields=['-created']),
		]

This way when you query your Orders and sort them based on created field, the sorting will be faster as this field is now indexed.

However, as with almost everything there are trade-offs to consider. Creating and maintaining indexes requires additional storage space. Indexes should be used mainly with fields that will be most often used for searching and sorting your data.