python 30 lines · 1 tab

Django query optimization with only and defer

Priya Sharma Jan 2026
1 tab
from blog.models import Post


# Load only specific fields
posts = Post.objects.only('id', 'title', 'published_at')
for post in posts:
    print(post.title)  # No extra query
    # print(post.content)  # Would trigger extra query


# Exclude large fields
posts = Post.objects.defer('content', 'raw_content')
for post in posts:
    print(post.title)  # No extra query
    # Accessing content would trigger query


# Combine with select_related
posts = Post.objects.select_related('author').only(
    'id', 'title', 'author__username'
)


# For API responses
def get_post_list_data():
    return Post.objects.only(
        'id', 'title', 'slug', 'published_at', 'author_id'
    ).select_related('author').only(
        'author__id', 'author__username'
    )
1 file · python Explain with highlit

The only() method loads specified fields only, while defer() excludes specified fields. This reduces data transfer and memory usage. I use only() when I need just a few fields from large models. For read-only displays, this prevents loading unnecessary data. I'm careful with deferred fields—accessing them causes additional queries. For JSON APIs, only() with serializer fields prevents over-fetching. I combine with select_related() for efficient joins. These optimizations are crucial for models with many or large fields.


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 query optimization with only and defer — share card
Link copied