python 33 lines · 1 tab

Django database indexes for query performance

Priya Sharma Jan 2026
1 tab
from django.db import models
from django.contrib.postgres.indexes import GinIndex, BTreeIndex


class Order(models.Model):
    customer = models.ForeignKey('Customer', on_delete=models.CASCADE)
    status = models.CharField(max_length=20, db_index=True)
    total = models.DecimalField(max_digits=10, decimal_places=2)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    completed_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        indexes = [
            # Compound index for common query
            models.Index(fields=['customer', 'status']),

            # Descending order index
            models.Index(fields=['-created_at']),

            # Partial index (PostgreSQL)
            models.Index(
                fields=['completed_at'],
                condition=models.Q(status='completed'),
                name='completed_orders_idx'
            ),

            # Covering index (includes extra columns)
            models.Index(
                fields=['status'],
                include=['total', 'created_at'],
                name='status_cover_idx'
            ),
        ]
1 file · python Explain with highlit

Database indexes dramatically speed up queries. I add indexes to frequently-filtered fields via db_index=True or Meta.indexes. Compound indexes help queries filtering on multiple fields together. For text search on PostgreSQL, I use GinIndex with SearchVector. I check if indexes are used with EXPLAIN. Too many indexes slow down writes, so I profile before adding. Partial indexes with condition reduce index size. For large tables, I create indexes concurrently in production. This is the first optimization for slow queries.


Related snips

python
import os
import stat

for root, _dirs, files in os.walk('/etc'):
    for name in files:
        path = os.path.join(root, name)

Python security audit script for exposed risky filesystem state

python auditing host-security
by Kai Nakamura 1 tab
python
class Product(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    cost = models.DecimalField(max_digits=10, decimal_places=2)
    margin = models.DecimalField(max_digits=5, decimal_places=2, blank=True)

Django model signals vs overriding save

django python models
by Priya Sharma 2 tabs
ruby
require "csv"

class PeopleCsvStream
  include Enumerable

  HEADERS = %w[id full_name email signed_up_at plan].freeze

Resilient CSV Export as a Streamed Response

rails performance streaming
by codesnips 3 tabs
ruby
Rails.application.configure do
  config.after_initialize do
    Bullet.enable = true
    Bullet.alert = false
    Bullet.bullet_logger = true
    Bullet.console = true

N+1 query detection with Bullet gem

rails performance activerecord
by Alex Kumar 2 tabs
python
from django.urls import path
from . import views

app_name = 'blog'

urlpatterns = [

Django URL namespacing and reverse lookups

django python urls
by Priya Sharma 3 tabs
ruby
# Vulnerable: user input is concatenated directly into SQL.
email = params[:email]
password = params[:password]

sql = "SELECT * FROM users WHERE email = '#{email}' AND password_hash = '#{password}'"
user = ActiveRecord::Base.connection.execute(sql).first

SQL injection prevention with unsafe and safe query patterns

sql-injection owasp database
by Kai Nakamura 3 tabs

Share this code

Here's the card — post it anywhere.

Django database indexes for query performance — share card
Link copied