Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: show/log ORM sql calls from python shell

Tags:

orm

django

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?

like image 340
Parand Avatar asked Feb 22 '10 22:02

Parand


People also ask

How do I log a query in Django?

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.

What is Django's ORM?

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.

Is Django ORM slow?

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.


2 Answers

If you're using Django 1.3:

import logging l = logging.getLogger('django.db.backends') l.setLevel(logging.DEBUG) l.addHandler(logging.StreamHandler()) 
like image 98
jacobian Avatar answered Oct 13 '22 00:10

jacobian


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.

like image 39
babbageclunk Avatar answered Oct 12 '22 23:10

babbageclunk