Supercharge Your Django App: 7 Sneaky Tricks to Crush Slow Database Queries

Optimizing Django query performance is critical for building performant web applications. Django provides many tools and methods for optimizing database queries in its Database access optimization documentation. In this blog post, we will explore a collection of additional and essential tips I’ve compiled over the years to help you pinpoint and resolve your inefficient Django queries. Kill Long-Running Queries with a Statement Timeout PostgreSQL supports a statement_timeout parameter that allows you to set a maximum time limit per query....

August 13, 2023 · 6 min · Johnny Metz

Why you need to use Subqueries in Django

The Django ORM is a powerful tool but certain aspects of it are counterintuitive, such as the SQL order of execution. Let’s look at an example of this trap and how we can fix it using subqueries: class Book(models.Model): class Meta: constraints = [ models.UniqueConstraint( fields=["name", "edition"], name="%(app_label)s_%(class)s_unique_name_edition", ) ] name = models.CharField(max_length=255) edition = models.CharField(max_length=255) release_year = models.PositiveIntegerField(null=True) I want to write a query that reads: Out of the latest books, give me the ones with a non-null release year....

July 21, 2021 · 2 min · Johnny Metz

Find all N+1 violations in your Django app

The N+1 problem is a common database performance issue. It plagues ORM’s, such as Django and SQLAlchemy, because it leads to your application making more database queries than necessary. Let’s look at a basic example in Django. class Artist(models.Model): name = models.CharField(max_length=255) class Song(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE) name = models.CharField(max_length=255) def print_songs(): for song in Song.objects.all(): print(f"{song.artist.name} - {song.name}") Now let’s create a unit test to ensure print_songs runs successfully....

April 13, 2021 · 3 min · Johnny Metz