Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

django

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.

like image 599
Mihai Oprea Avatar asked Mar 28 '12 14:03

Mihai Oprea


People also ask

What does save () return in Django?

Creating objects Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

How do I see query in Django ORM?

To do so, open the Django shell to run the query. You might be wonder how Django ORM makes our queries executed or what the corresponding query of the code we are writing. It is quite simple to get the SQL query, we need to use the str() and pass the queryset object along with query.

How can you see raw SQL queries running in Django?

Django gives you two ways of performing raw SQL queries: you can use Manager. raw() to perform raw queries and return model instances, or you can avoid the model layer entirely and execute custom SQL directly. Explore the ORM before using raw SQL!


2 Answers

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!

like image 54
StefanNch Avatar answered Oct 17 '22 04:10

StefanNch


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

like image 44
Sid Avatar answered Oct 17 '22 04:10

Sid