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

Optimize Django Query Performance by combining Select Related and Prefetch Related

Introduction When building a Django application, one of the key challenges developers face is optimizing database query performance. Django provides two tools,select_related and prefetch_related, that reduce the number of database queries, and increase the performance of your application. This blog post explores the power of these two methods and how to combine them to maximize your application’s query performance. My team at PixieBrix implemented these techniques and have seen a significant improvement in query performance and customer satisfaction....

May 13, 2023 · 3 min · Johnny Metz

[Cross-Post] Django performance: Sort by a Custom Order

See the post here: Sort a Django Queryset by a Custom Order

January 2, 2023 · 1 min · Johnny Metz

Free up Django CPU usage in Docker with Watchman

You can use watchman in your Django project to make auto-reloads more CPU efficient. Adam Johnson’s Efficient Reloading in Django’s Runserver With Watchman blog post does an excellent job describing how to set this up. I highly recommend giving it a read. The tutorial explains how to install watchman on macOS with brew install watchman but does not explain how to install it in a Python docker container. Considering all of my Django projects are dockerized, I decided to figure it out....

January 4, 2022 · 2 min · Johnny Metz

Set Django Model Field Choices in your Frontend the Right Way

In Django, you can define a set of choices for any field. If you’re using a SPA frontend, such as React or Vue, then you’ll need to access these choices in a form. Let’s look at two ways to do this. As an example, we’ll use the following Device model: class Device(models.Model): class Size(models.TextChoices): SMALL = "S" MEDIUM = "M" LARGE = "L" name = models.CharField(max_length=255) size = models.CharField(max_length=255, choices=Size.choices) Hardcode choices in frontend The fastest approach is to harcode these choices in the frontend....

December 1, 2021 · 2 min · Johnny Metz