Database Performance Check - Django

An experiment with Django Models

Single Model × Multiple Models × Indexed Model

Ilustration


 

Understanding the experiment context


In this experience all the models contain one single field, name, which will contain a 25 characters string randomly generated. 

class UserProfile(models.Model):
    name = models.CharField(max_length=100, blank=True, null=True)

 

Single Model


A model named UserProfileRoot contains100.000 entries with their respective name.

single = []
start_time = time.perf_counter()
        
name = UserProfileRoot.objects.get(name = lookup_name).name

run_time = time.perf_counter() - start_time

single.append(run_time)

 


Multiple Models
 

The same dataset is then distributed across ten different models, UserProfile1 to UserProfile10, each containing 10,000 entries.

In this scenario, the query checks each model until a match is found.

models = [
    UserProfile1,
    UserProfile2,
    UserProfile3,
    UserProfile4,
    UserProfile5,
    UserProfile6,
    UserProfile7,
    UserProfile8,
    UserProfile9,
    UserProfile10
]

multiple = []

start_time = time.perf_counter()

obj = None

for model in models:
    obj = model.objects.filter(name=lookup_name).first()
    if obj:
        break

run_time = time.perf_counter() - start_time

multiple.append(run_time)


Indexed Model
 

Most relational databases implement indexes using B-tree structures.
This allows the database engine to quickly locate rows by navigating the index instead of scanning the entire table.

class UserProfileIndex(models.Model):
    name = models.CharField(max_length=100, blank=True, null=True)
    class Meta:
        indexes = [
            models.Index(fields=["name"]),
        ]

 

index = []

start_time = time.perf_counter()
      
name = UserProfileIndex.objects.get(name = lookup_name).name

run_time = time.perf_counter() - start_time

index.append(run_time)

 

 

Conclusion

The average query time for the single model:
6.6 milliseconds

The average query time for the multiple models:
4.8 milliseconds

The average query time for the indexed model:
0.3 milliseconds

 

Note: These results should be interpreted as relative comparisons, since absolute timings depend on the hardware and environment where the benchmark is executed.

 

In this experiment, indexing the queried field had a significantly greater impact on performance than distributing the data across multiple models.


Django