python 39 lines · 1 tab

Django raw SQL queries for complex operations

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


def get_top_authors(limit=10):
    """Get authors with most published posts using raw SQL."""
    query = """
        SELECT
            u.id,
            u.username,
            COUNT(p.id) as post_count
        FROM auth_user u
        INNER JOIN blog_post p ON u.id = p.author_id
        WHERE p.status = %s
        GROUP BY u.id, u.username
        ORDER BY post_count DESC
        LIMIT %s
    """

    with connection.cursor() as cursor:
        cursor.execute(query, ['published', limit])
        columns = [col[0] for col in cursor.description]
        return [dict(zip(columns, row)) for row in cursor.fetchall()]


def get_monthly_stats():
    """Use raw() to get Post objects with aggregations."""
    query = """
        SELECT
            id,
            title,
            author_id,
            DATE_TRUNC('month', published_at) as month
        FROM blog_post
        WHERE status = %s
        ORDER BY published_at DESC
    """

    return Post.objects.raw(query, ['published'])
1 file · python Explain with highlit

For queries too complex for the ORM, I use raw SQL. The raw() method returns model instances. I use cursor.execute() for non-model queries. I always use parameterized queries to prevent SQL injection—never string interpolation. For reporting, raw SQL is often clearer than complex ORM chains. I document why raw SQL is needed so future developers understand. For database-specific features like window functions, raw SQL is sometimes the only option. I test raw queries against multiple database backends if the app supports them.


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
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
ruby
# BAD: N+1 query problem
@users = User.all
@users.each do |user|
  puts user.posts.count  # Fires query for each user!
end

ActiveRecord query optimization and N+1 prevention

ruby rails activerecord
by Sarah Mitchell 3 tabs
python
import graphene
from graphene_django import DjangoObjectType
from blog.models import Post, Comment


class PostType(DjangoObjectType):

Django GraphQL with Graphene

django python graphql
by Priya Sharma 2 tabs

Share this code

Here's the card — post it anywhere.

Django raw SQL queries for complex operations — share card
Link copied