0
0
DjangoHow-ToBeginner · 4 min read

How to Use Raw SQL in Django: Syntax and Examples

In Django, you can use Model.objects.raw() to run raw SQL queries that return model instances, or use django.db.connection.cursor() to execute custom SQL directly. These methods let you run SQL when Django's ORM doesn't fit your needs.
📐

Syntax

Django provides two main ways to run raw SQL:

  • Using raw(): Runs a raw SQL query and returns model instances.
  • Using connection.cursor(): Executes any SQL command directly and returns raw results.

Each method has its own syntax and use cases.

python
from django.db import connection

# Using raw() with a model
MyModel.objects.raw('SELECT * FROM myapp_mymodel WHERE id = %s', [1])

# Using connection.cursor() for custom SQL
with connection.cursor() as cursor:
    cursor.execute('SELECT * FROM myapp_mymodel WHERE id = %s', [1])
    row = cursor.fetchone()
💻

Example

This example shows how to fetch records using raw() and how to execute a custom SQL query with connection.cursor().

python
from django.db import connection
from myapp.models import MyModel

# Using raw() to get model instances
for obj in MyModel.objects.raw('SELECT * FROM myapp_mymodel WHERE id < %s', [5]):
    print(obj.id, obj.name)

# Using connection.cursor() for custom SQL
with connection.cursor() as cursor:
    cursor.execute('SELECT COUNT(*) FROM myapp_mymodel')
    count = cursor.fetchone()[0]
    print('Total records:', count)
Output
1 ExampleName 2 AnotherName 3 ThirdName 4 FourthName Total records: 10
⚠️

Common Pitfalls

Common mistakes when using raw SQL in Django include:

  • Not using parameterized queries, which risks SQL injection.
  • Expecting raw() to work with queries that don't return all model fields.
  • Forgetting to close the cursor or not using with statement.
  • Trying to use ORM features like filtering or ordering on raw query results.

Always use parameter placeholders (%s) and pass parameters as a list or tuple.

python
from django.db import connection

# Wrong: unsafe string formatting (vulnerable to SQL injection)
user_id = 1
query = f"SELECT * FROM myapp_mymodel WHERE id = {user_id}"
with connection.cursor() as cursor:
    cursor.execute(query)  # Avoid this

# Right: use parameterized query
with connection.cursor() as cursor:
    cursor.execute('SELECT * FROM myapp_mymodel WHERE id = %s', [user_id])
📊

Quick Reference

Summary tips for using raw SQL in Django:

  • Use Model.objects.raw() for SELECT queries returning model instances.
  • Use connection.cursor() for any SQL commands (SELECT, INSERT, UPDATE, DELETE).
  • Always use parameterized queries to avoid SQL injection.
  • Use with connection.cursor() to ensure proper resource management.
  • Raw SQL bypasses ORM features like automatic escaping and migrations.

Key Takeaways

Use Model.objects.raw() to run raw SELECT queries returning model instances.
Use connection.cursor() with parameterized queries for custom SQL commands.
Always use parameter placeholders (%s) to prevent SQL injection.
Wrap cursor usage in a with statement to manage resources safely.
Raw SQL bypasses Django ORM features, so use it only when necessary.