Here’s a quick tutorial on how to excecute raw SQL queries in Django.

Django provides a really awesome orm. And most of the time, the orm provides everything you need to query the database. However, there can be certain cases where you might want to execute a raw SQL query. For example, there can be situations where the SQL generated the Django orm is not efficient enough or it’s simply easier to write the query in raw SQL rather than having to fight with the orm. For such cases, Django gives us a way to execute SQL directly.

Here’s a basic example with some included comments that explain what each line does.

Basic Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from django.db import connection

# get a cursor object from the database connection
cursor = connection.cursor()

# my_query is a string with the SQL you want executed
cursor.execute(<my_query>)

#you can fetch the next row using the cursors fetchone method
row = cursor.fetchone()

#you can also get all results by using the fetchall method
row = cursor.fetchall()

#make sure to clean up
cursor.close()

Pretty cool right? Django makes it pretty easy to execute SQL on your database.

Django also allows you to use the cursor object as a context manager. This is useful because it will automatically close the cursor for you.

Using A Context Manager

1
2
3
4
5
6
from django.db import connection

with connection.cursor() as cursor:
    cursor.execute(<my_query>)
    row = cursor.fetchall()
    # ... rest of code

I love how flexible Django is. Although you will use the Django orm in most cases, you do have the ability to easily execute SQL if you need to.

If you enjoyed this content and are interested in more reading more django content, please take a look at my Django Commands Cheat Sheet, which shows and explains commands that are integral to the Django development workflow.