Using the excellent Django-Devserver I'm finding all kinds of interesting and unexpected SQL calls in my code. I wanted to find where the calls are coming from, and so I'm looking for a way to get a log or print-out of all SQL calls generated by the Django ORM in the Python shell. That is, when I do a Django ORM call via the Python shell, I'd like to see the resulting SQL printed out or logged.
I noticed several solutions that add log info to the html page. Is there an easy way to dump to the command line instead?
Logging all SQL queries LOGGING = { ... 'handlers': { ... 'console': { 'level': 'DEBUG', 'class': 'logging. StreamHandler', }, ... }, ... } Next, you'll need to add a logger that logs to this handler: LOGGING = { ... 'loggers': { ... 'django.
One of the most powerful features of Django is its Object-Relational Mapper (ORM), which enables you to interact with your database, like you would with SQL. In fact, Django's ORM is just a pythonical way to create SQL to query and manipulate your database and get results in a pythonic fashion.
Django's ORM is fantastic. It's slow because it chooses to be convenient but if it needs to be fast it's just a few slight API calls away. If you're curious, check out the code on Github.
If you're using Django 1.3:
import logging l = logging.getLogger('django.db.backends') l.setLevel(logging.DEBUG) l.addHandler(logging.StreamHandler())
I was trying to use "Django: show/log ORM sql calls from python shell" in a shell on a production server, and it wasn't working. Eventually someone pointed out that it will only do this debug logging when DEBUG = True
. But you can work around that like this:
import logging from django.db import connection connection.force_debug_cursor = True # Change to use_debug_cursor in django < 1.8 l = logging.getLogger('django.db.backends') l.setLevel(logging.DEBUG) l.addHandler(logging.StreamHandler())
I'm leaving this here so I can find it later, and hopefully it saves someone else the same digging I did.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With