Making Django Web Application Faster
Table of contents
In a recent project of building an e-commerce web app in Django, some requests were relatively slow when retrieving items from the database, especially when using query filtering.
To overcome this challenge, I used database indexes to improve performance for query filtering or ordering results by this field. A database index is a data structure that improves the speed of data retrieval operations on a database table. An index is created on one or more table columns, providing a quick way to look up rows based on the indexed column values.
How to implement in Django
To implement database indexing in Django, I created a Meta class inside the model class, and inside the class a variable list called indexes that contains the fields to be indexed. Here is a snippet of the implementation.
# this class is defined inside a Model Class in this case a Product class
class Meta:
indexes = [
models.Index(fields=['id', 'slug']),
models.Index(fields=['name']),
models.Index(fields=['-created']),
]
In the implementation above, the indexes option defines database indexes for our Product model which contains the fields; id, slug, name, and created(in descending order). The indexes could also be defined as function expressions and database functions.
The creation of indexes will be included in the database migrations.
HNG 11 internship
I am excited about gaining practical and real-world experience from projects offered by HNG during the internship after months of continuous learning and building guided projects. After failing to complete the internship twice, I am looking forward to conquering previous challenges and unlocking new levels as I continue to strengthen my skills.
Subscribe to my newsletter
Read articles from Nickson K Rop directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by