Skip to content

Instantly share code, notes, and snippets.

@nkanaev
Last active January 28, 2019 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkanaev/4f79d4307372e2b3ffa5577a65d28245 to your computer and use it in GitHub Desktop.
Save nkanaev/4f79d4307372e2b3ffa5577a65d28245 to your computer and use it in GitHub Desktop.
def rawsql(queryset):
compiler = queryset.query.get_compiler(using=queryset.db)
sql, params = compiler.as_sql()
with compiler.connection.cursor() as cursor_wrapper:
cursor = cursor_wrapper.cursor
cursor_type = str(type(cursor)).lower()
if 'psycopg2' in cursor_type or 'pymysql' in cursor_type:
return cursor.mogrify(sql, params)
elif 'mysqldb' in cursor_type:
db = cursor._get_db()
if isinstance(params, dict):
return query % {k: db.literal(v) for k, v in params.items()}
else:
return query % tuple(map(db.literal, params))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment