Django’s ORM handles most queries well, but complex reports, database-specific functions, or an ORM query that runs too slowly call for raw SQL. Use Model.objects.raw() when the result is still model instances, connection.cursor() when you need aggregate numbers, and always pass parameters through %s — fast and safe from SQL injection.

The Problem

Say you need a report of the “top 5 discounted products, sorted by price after discount”. Many developers reach for the obvious: pull the whole table into Python, then filter and sort. That works fine with a few hundred rows, but with millions of rows it eats RAM and runs slowly because all the computation lands on the app server.

Worse is building the SQL string with an f-string from user input. A single ' in the search box breaks the query structure — and an attacker can read or delete data through SQL injection.

Bad code: filtering and sorting in Python

# SLOW: pulls everything into Python, then computes
products = Product.objects.all()
cheap = [p for p in products if p.price * (1 - p.discount / 100) < 1_000_000]
cheap.sort(key=lambda p: p.price)

Bad code: building SQL with an f-string

# DANGEROUS: direct string concatenation — SQL injection
keyword = request.GET.get("q", "")
with connection.cursor() as cursor:
cursor.execute(f"SELECT id, name, price FROM shop_product WHERE name LIKE '%{keyword}%'")

The Solution

When the result is still model instances, use objects.raw(): you write the SQL by hand, but Django maps the result back to the right model. Note that the SELECT must include the primary key, and an extra computed column like final_price becomes an attribute on each object.

When you need aggregate numbers not tied to any model — for example, counting products and the average price per category — use connection.cursor(): fetchall() returns plain tuples, compact for reports.

The key point is parameters: always write the %s placeholder in the SQL and pass values as the second argument to execute(). Django converts %s to the right placeholder for each database and escapes values before sending them. An attack string like ' OR '1'='1 then becomes just a harmless search string that returns 0 rows. Never use f-strings or the % operator to splice values into SQL — that is exactly the door SQL injection walks through.

One last note: raw SQL ties you to a specific dialect — PostgreSQL date functions differ from MySQL’s, for example — so gather your raw SQL queries in one place and test against the same database you run in production.

Correct code: objects.raw() with a computed column

products = Product.objects.raw(
"SELECT id, name, price, price * (1 - discount / 100.0) AS final_price "
"FROM shop_product WHERE discount > 0 ORDER BY final_price DESC LIMIT 5"
)
for p in products:
print(p.name, p.final_price) # final_price is an extra computed attribute

Correct code: cursor() for aggregate reports

from django.db import connection
with connection.cursor() as cursor:
cursor.execute(
"SELECT category, COUNT(*) AS total, AVG(price) AS avg_price "
"FROM shop_product GROUP BY category ORDER BY total DESC"
)
rows = cursor.fetchall() # list of tuples: (category, total, avg_price)

Correct code: parameterized %s, safe from SQL injection

keyword = request.GET.get("q", "")
with connection.cursor() as cursor:
cursor.execute(
"SELECT id, name, price FROM shop_product WHERE name LIKE %s",
["%" + keyword + "%"],
)
rows = cursor.fetchall()

Putting It Into Practice

Keep the ORM as the default and reach for raw SQL for only three jobs: aggregate reports, queries that use database-specific functions, and queries you have measured as too slow when generated by the ORM. Put raw SQL queries in a custom Manager so they are reusable, and write tests that run against the same database as production.

Related Posts

FAQ

When should I use raw SQL instead of the ORM?

When a query is too complex to express with the ORM, when you need a database-specific function, or when you have measured the ORM-generated query as slow. Otherwise, the ORM is shorter and safer.

How is objects.raw() different from connection.cursor()?

raw() returns model instances, so you can keep using them in templates and business logic — but the SELECT must include the primary key. cursor() returns raw tuples, compact for reports but without any model methods.

Is the %s placeholder safe on every database?

Yes. Django converts %s to the correct placeholder for the backend — ? on SQLite, for example — and escapes values before sending them. You only need to avoid splicing strings into the SQL yourself.

💬 Have you tried this approach in your own project? If you ran into an error or know a more concise way to do it, leave a comment below — I read every one and will add the best ideas to the post.

Sources