views:

166

answers:

1

How can you get the SQL for a Django model's .save(), i.e.

from django.db import models

class MyM(models.Model):
   text = models.TextField()

How can you get the SQL that would be created/used in the following scenario:

 >>> m = MyM(text="123")
 >>> m.save()
 # What SQL Django just run?

Thanks!

+1  A: 

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.

DrDee
Thanks, DrDee. Would the most recent query then be db.queries[-1]? (or, if that's an iterator, list(db.queries)[-1])?
Brian M. Hunt
Here's the FAQ in question: http://docs.djangoproject.com/en/dev/faq/models/#how-can-i-see-the-raw-sql-queries-django-is-running -- note it's `from django.db import connection` and `connection.queries`
Brian M. Hunt
I suspect db.queries[-1], but just give it a shot and see what happens.
DrDee
@DrDee For no apparent reason the INSERTs aren't showing up ... but SELECTs are. Strange. I'll tinker. In any event - this ought to work - thanks.
Brian M. Hunt