Skip to content
Advertisement

Get SQL a Django model has (or would call) on .save()

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!

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement