Django Raw SQL Queries
This prevents SQL injection
Manager.raw¶
Direct database¶
from django.db import connection
with connection.cursor() as cursor:
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
row = cursor.fetchone()
rows = cursor.fetchall()
def dictfetchall(cursor):
"Return all rows from a cursor as a dict"
columns = [col[0] for col in cursor.description]
return [
dict(zip(columns, row))
for row in cursor.fetchall()
]
Using SQLAlchemy to help with raw SQL¶
import sqlalchemy
from sqlalchemy.dialects import postgresql
statement = sqlalchemy.text(text) # sqlalchemy.sql.elements.TextClause
# :my_var_name -> %(my_var_name)s
result = str(statement.compile(dialect=postgresql.dialect()))
Last update:
2023-04-24