Categories
Python Answers

How to run raw SQL queries in Python Django views?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *