Executing raw SQL in Django

October 20, 2012 · Posted in Development 

Sometimes you need to run a custom SQL query and return results that do not correspond to your model or make SQL queries to UPDATE or DELETE directly on a database.

Some scenarious:

- make a specific SELECT query and return a list of rows which are dictionaries (not objects of a model)

- make UPDATE or DELETE queries



use connection object from from django.db as follows:


SELECT with raw SQL

In case when you have a model and want to make a SELECT query and return a list of objects of your model you can do like this:

persons = Person.objects.raw(“SELECT * FROM mytablename WHERE .. GROUP BY .. ORDER BY ..”)

Sometimes, we want to invoke a SELECT query against your databse and return a generic list of rows that do not correspond to your model.
The following example shows how to retrieve a list of dictionaries with keys for the column values.

This code example is based on this: http://blog.doughellmann.com/2007/12/using-raw-sql-in-django.html



Read more: