The Django db_default Gotcha That Breaks Your Code

Starting in Django 5.0, you can use db_default to define database-level default values for model fields. It’s a great feature but comes with a subtle and dangerous gotcha that can silently break your code before the object is ever saved. The Gotcha in Action Let’s say you’re building a simple task manager, and you want to track whether a task is completed: from django.db import models class Task(models.Model): is_completed = models.BooleanField(db_default=False) The db_default option ensures the database applies the default in raw INSERT queries and prevents errors during a rolling deployment. ...

August 3, 2025

Stop Using Django's squashmigrations: There's a Better Way

Squashing merges multiple database migrations into a single consolidated file to speed up database setup and tidy up history. Django’s squashmigrations command promises to handle this, but it’s error-prone and unnecessarily complex. A clean reset is faster and simpler. ⚠️ Why squashmigrations Falls Short Broken in Practice In medium-to-large projects, I’ve consistently seen squashmigrations generate poor results, such as failing to optimize basic no-ops (like adding and deleting the same field) and even breaking migrations. The official docs acknowledge this: ...

July 26, 2025

Speed Up Django Queries with values() over only()

If your Django queries feel slow, the problem might not be your database — it might be your ORM. Recently, I was working with a query that took 25 seconds to run through the Django ORM, but the underlying SQL completed in just 2 seconds. With a single change, I got the ORM query down to 2 seconds as well — and reduced the memory footprint by 70%. Let’s walk through what happened, and why using .values() instead of .only() can dramatically improve performance. ...

June 29, 2025

Avoiding PostgreSQL Pitfalls: The Hidden Cost of Failing Inserts

A simple insert query turned into a silent performance killer. Our frontend pings our server every few minutes to track device activity. Each ping attempts to insert a row into a DevicePingDaily table, which has a unique constraint on (device_id, date) to ensure only one record per device per day. In Django, the logic looked like this: try: DevicePingDaily.objects.create(device=device, date=today) except IntegrityError: pass It seemed harmless. But as traffic grew, latency spiked and API timeouts increased. Observability tools quickly pointed to the culprit: ...

June 15, 2025

5 Ways to Get the Latest Book Per Author in Django

In a Django application, fetching the latest record for each group is a common yet challenging task, especially when working with large datasets. Whether you’re building an analytics dashboard or managing grouped data, finding an efficient solution is key. In this blog post, we’ll explore five different approaches to tackle this problem, ranked from least to most effective based on performance and readability, using the following Book model: class Book(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey( Author, on_delete=models.CASCADE, related_name="books" ) genre = models.CharField(max_length=255) published_at = models.DateTimeField() is_featured = models.BooleanField(default=False) Solution 1: Python Max with Prefetch latest_books = [ max(author.books.all(), key=lambda x: x.published_at, default=None) for author in Author.objects.prefetch_related("books") ] Performs heavy computation in Python rather than leveraging the database, which is bad for performance. Also makes two database queries (better solutions do it in one). ...

November 14, 2024