Executing raw SQL directly in Django


In Django most of the time we use model query API. But sometimes we need to run raw SQL queries directly.

Raw SQL queries

To perform raw sql queries we need start with importing django.db.connection into your python file. django.db.connection object is the system's default database connection.
Now for executing the raw query we need use a cursor object, for that we need to use the connection.cursor(). Now, cursor.execute(sql) can execute the raw query and cursor.fetchall() will return all the results as a class list.

Here is an example,

For detailed django raw SQL documentations, you can visit here.

comments powered by Disqus