How can I see the raw SQL queries Django is running?
See the docs FAQ: "How can I see the raw SQL queries Django is running?"
django.db.connection.queries
contains a list of the SQL queries:
from django.db import connection
print(connection.queries)
Querysets also have a query
attribute containing the query to be executed:
print(MyModel.objects.filter(name="my name").query)
Note that the output of the query is not valid SQL, because:
"Django never actually interpolates the parameters: it sends the query and the parameters separately to the database adapter, which performs the appropriate operations."
From Django bug report #17741.
Because of that, you should not send query output directly to a database.
If you need to reset the queries to, for example, see how many queries are running in a given period, you can use reset_queries
from django.db
:
from django.db import reset_queries
reset_queries()
print(connection.queries)
>>> []
Django how to see generated SQL query?
How about using logging?
you can add this in settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': True,
},
},
}
and you can add this in your any views.py
import logging
l = logging.getLogger('django.db.backends')
l.setLevel(logging.DEBUG)
l.addHandler(logging.StreamHandler())
In your console, you can check SQL query.
Another way
go shell
python manage.py shell
>>from yourmodel import Example
>>queryset = Example.objects.all()
>>print(queryset.query)
you can see raw query string.
Django+Raw Sql Query: See raw sql query running behind Django ORM in get method
You can use django.db.connection.queries
to check db queries if you don't want to configure LOGGING:
from django import db
from app.models import MyModel
MyModel.objects.get(id=1)
print db.connection.queries
>>> [{'sql': 'Your query here', 'time': '0.001'}]
By the way, get
method uses filter
with slice from _result_cache
under the hood and returns this slice. Also sometimes it also apply order_by
to queryset. So you can almost always predict your SQL by checking query of filter
method with same arguments.
How to exhaustively see queries Django is running?
You can try changing LOGGING
config, for example in your settings.py
(logs all your queries if you DEBUG
is True
):
LOGGING = {
'version': 1,
'filters': {
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
}
},
'handlers': {
'console': {
'level': 'DEBUG',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
}
},
'loggers': {
'django.db.backends': {
'level': 'DEBUG',
'handlers': ['console'],
}
}
}
Getting the SQL from a Django QuerySet
You print the queryset's query
attribute.
>>> queryset = MyModel.objects.all()
>>> print(queryset.query)
SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel"
Raw SQL queries in Django views
>>> from django.db import connection
>>> cursor = connection.cursor()
>>> cursor.execute('''SELECT count(*) FROM people_person''')
1L
>>> row = cursor.fetchone()
>>> print row
(12L,)
>>> Person.objects.all().count()
12
use WHERE clause to filter vote for yes:
>>> cursor.execute('''SELECT count(*) FROM people_person WHERE vote = "yes"''')
1L
Related Topics
Commit Data in a MySQL Container
If' in 'Select' Statement - Choose Output Value Based on Column Values
How to Select the Nth Row in a SQL Database Table
How to Update Two Tables in One Statement in SQL Server 2005
Computed/Calculated/Virtual/Derived Columns in Postgresql
Return Row With the Max Value of One Column Per Group
Why Does Null = Null Evaluate to False in SQL Server
Querying Spark SQL Dataframe With Complex Types
How to Comma Delimit Multiple Rows into One Column
Postgresql Group_Concat Equivalent
MySQL: Alternatives to Order by Rand()
Is the SQL Where Clause Short-Circuit Evaluated
Select Top 10 Records For Each Category