Sometimes even Manager.raw()
isn't quite enough: you might need to perform queries that don't map cleanly to models, or directly execute UPDATE
, INSERT
, or DELETE
queries. In these cases, you can always access the database directly, routing around the model layer entirely. The object django.db.connection
represents the default database connection. To use the database connection, call connection.cursor()
to get a cursor object. Then, call cursor.execute(sql, [params])
to execute the SQL and cursor.fetchone()
or cursor.fetchall()
to return the resulting rows. For example:
from django.db import connection def my_custom_sql(self): cursor = connection.cursor() cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz]) cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz]) row = cursor.fetchone() return row
Note that if you want to include literal percent signs in the query...