Get SQL a Django model has (or would call) on .save()
If you want get the insert statement for model before saving - you can use the following code (checked on django 1.4)
from django.db import connection
from django.db.models import sql
def object_to_query(objects):
if isinstance(objects, (list, tuple)
values = obj._meta.local_fields
q = sql.InsertQuery(obj)
q.insert_values(values, [obj])
compiler = q.get_compiler('default')
# Normally, execute sets this, but we don't want to call execute
setattr(compiler, 'return_id', False)
stmts = compiler.as_sql()
stmt = [stmt % params for stmt, params in stmts]
return stmt[0]
From the Django FAQ:
How can I see the raw SQL queries Django is running? Make sure your Django DEBUG setting is set to True. Then, just do this:
>>> from django.core.db import db
>>> db.queries
[{'sql': 'SELECT polls_polls.id,polls_polls.question,polls_polls.pub_date FROM polls_polls',
'time': '0.002'}]
db.queries is only available if DEBUG is True. It's a list of dictionaries in order of query execution. Each dictionary has the following:
sql
--The raw SQL statement
time
-- How long the statement took to execute, in seconds.
db.queries includes all SQL statements -- INSERTs, UPDATES, SELECTs, etc.
Just run python manage.py sqlall APP_NAME
.