How to See the Raw SQL Queries Django Is Running

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



Leave a reply



Submit