Sometimes, we want to run raw SQL queries in Python Django views.
In this article, we’ll look at how to run raw SQL queries in Python Django views.
How to run raw SQL queries in Python Django views?
To run raw SQL queries in Python Django views, we can use the cursor.execute
method.
For instance, we write
from django.db import connection
cursor = connection.cursor()
cursor.execute('''SELECT count(*) FROM people_person''')
row = cursor.fetchone()
to get the cursor
with connection.cursor
.
Then we call cursor.execute
to run a raw select query.
And then we get the first row returned with cursor.fetchone
.
Conclusion
To run raw SQL queries in Python Django views, we can use the cursor.execute
method.