Mihai Oprea
Mihai Oprea

Reputation: 2047

How do I print the queries executed by django .save() method?

I want to see what queries are executed on django's model .save() method. Since I am in a production environment, I can't use Django Toolbar for this.

Upvotes: 8

Views: 7799

Answers (2)

Sid
Sid

Reputation: 7631

There are 2 ways:

  1. https://docs.djangoproject.com/en/dev/faq/models/#how-can-i-see-the-raw-sql-queries-django-is-running

  2. In Django 1.3 and above you can use logging which I believe dumps your sql queries into the log. https://docs.djangoproject.com/en/dev/topics/logging/

Doesn't seem like there's a straight-forward easy way without DEBUG=True. This is the closest I could find: Logging Django SQL queries with DEBUG set to False

Upvotes: 2

StefanNch
StefanNch

Reputation: 2609

Based on Sid's answer and this snippet (http://djangosnippets.org/snippets/1973/) i've replace the postgres db-wrapper with this:

# base.py
from django.db.backends.postgresql_psycopg2.base import *

#http://djangosnippets.org/snippets/1973/
class DatabaseWrapper(DatabaseWrapper):

    def __init__(self, *args, **kwargs):
        super(DatabaseWrapper, self).__init__(*args, **kwargs)
        self.use_debug_cursor = True

Then in settings.py, use 'ENGINE': 'my_project.db_backend', instead of the default backend (in my case, 'ENGINE': 'django.db.backends.postgresql_psycopg2',)

Now connection.queries will contain all your queries!

Upvotes: 5

Related Questions