230๐
Each QuerySet object has a query
attribute that you can log or print to stdout for debugging purposes.
qs = Model.objects.filter(name='test')
print(qs.query)
Note that in pdb, using p qs.query
will not work as desired, but print(qs.query)
will.
If that doesnโt work, for old Django versions, try:
print str(qs.query)
Edit
Iโve also used custom template tags (as outlined in this snippet) to inject the queries in the scope of a single request as HTML comments.
128๐
You also can use python logging to log all queries generated by Django. Just add this to your settings file.
LOGGING = {
'disable_existing_loggers': False,
'version': 1,
'handlers': {
'console': {
# logging handler that outputs log messages to terminal
'class': 'logging.StreamHandler',
'level': 'DEBUG', # message level to be written to console
},
},
'loggers': {
'': {
# this sets root level logger to log debug and higher level
# logs to console. All other loggers inherit settings from
# root level logger.
'handlers': ['console'],
'level': 'DEBUG',
'propagate': False, # this tells logger to send logging message
# to its parent (will send if set to True)
},
'django.db': {
# django also has database level logging
'level': 'DEBUG'
},
},
}
Another method in case application is generating html output โ django debug toolbar can be used.
- [Django]-How to add new languages into Django? My language "Uyghur" or "Uighur" is not supported in Django
- [Django]-Parsing unicode input using python json.loads
- [Django]-How to get Request.User in Django-Rest-Framework serializer?
116๐
You can paste this code on your Django shell which will display all the SQL queries:
import logging
l = logging.getLogger('django.db.backends')
l.setLevel(logging.DEBUG)
l.addHandler(logging.StreamHandler())
- [Django]-Using django-rest-interface
- [Django]-What is more efficient .objects.filter().exists() or get() wrapped on a try
- [Django]-How can I access environment variables directly in a Django template?
80๐
As long as DEBUG
is on:
from django.db import connection
print(connection.queries)
For an individual query, you can do:
print(Model.objects.filter(name='test').query)
- [Django]-Pylint "unresolved import" error in Visual Studio Code
- [Django]-Django โ "Incorrect type. Expected pk value, received str" error
- [Django]-Django rest framework, use different serializers in the same ModelViewSet
29๐
Maybe you should take a look at django-debug-toolbar
application, it will log all queries for you, display profiling information for them and much more.
- [Django]-What is a django.utils.functional.__proxy__ object and what it helps with?
- [Django]-Django fix Admin plural
- [Django]-Django development server reload takes too long
2๐
A robust solution would be to have your database server log to a file and then
tail -f /path/to/the/log/file.log
- [Django]-Django index page best/most common practice
- [Django]-Google Static Maps URL length limit
- [Django]-How can I avoid "Using selector: EpollSelector" log message in Django?
1๐
If you are using database routing, you probably have more than one database connection.
Code like this lets you see connections in a session.
You can reset the stats the same way as with a single connection: reset_queries()
from django.db import connections,connection,reset_queries
...
reset_queries() # resets data collection, call whenever it makes sense
โฆ
def query_all():
for c in connections.all():
print(f"Queries per connection: Database: {c.settings_dict['NAME']} {c.queries}")
# and if you just want to count the number of queries
def query_count_all()->int:
return sum(len(c.queries) for c in connections.all() )
- [Django]-What is a django.utils.functional.__proxy__ object and what it helps with?
- [Django]-How to delete project in django
- [Django]-Get protocol + host name from URL
-1๐
You can use a Django debug_toolbar to view the SQL query.
Step by step guide for debug_toolbar usage :
Install the Debug_toolbar
pip install django-debug-toolbar
Edit settings.py file & add debug_toolbar to Installed apps, this should be added below to โdjango.contrib.staticfilesโ. Also add debug_toolbar to Middleware.
Settings.py=>
INSTALLED_APPS= [ 'debug_toolbar']
MIDDLEWARE = ['debug_toolbar.middleware.DebugToolbarMiddleware']
create a new list named INTERNAL_IPS in settings.py file
Settings.py=> create new list at the end of settings.py file & add below list:
INTERNAL_IPS= [127.0.0.1']
This will allow the debug to run only on internal developement server
Edit urls.py file of #Project & add below code:
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls))
] + urlpatterns
apply migrate & run server again
You will see an add-on on your web page at 127.0.0.1 & if you click on SQL Query check box, you can actually see the run time of query as well.
- [Django]-Django Queryset with year(date) = '2010'
- [Django]-Django test app error โ Got an error creating the test database: permission denied to create database
- [Django]-How to stop autopep8 not installed messages in Code