Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django how do i view query in manage shell

Tags:

django

How can i see my django queries from manage shell interface

I have tried using this but gives me queries that pass through the django server

from django.db import connection
connection.queries()

I have seen it somewhere, can't remember where??

like image 345
gath Avatar asked Oct 07 '10 05:10

gath


3 Answers

Django how do i view query in manage shell

There are two ways to view the query in the shell. First, if you are using a queryset you can use the query attribute of the queryset. For e.g.

qs = MyModel.objects.all()
print(qs.query)

Second when the query is not visible immediately. For e.g. when you are updating a queryset using update(). In this case you can:

from django.db import connection
MyModel.objects.all().update(foo = 'bar')
print(connection.queries)
# print(connection.queries[-1]) # if you want to see only the last query

I have tried using this but gives me queries that pass through the django server

I don't understand what you mean by "gives me queries that pass through the Django server". Are you trying to see the queries while running the application? In that case use the django-debug-toolbar or the snippet referred to by @rubayeet.

like image 164
Manoj Govindan Avatar answered Sep 22 '22 00:09

Manoj Govindan


The easiest way is to use django extensions. You can install it with

$ pip install django-extensions

Start your shell with

./manage.py shell_plus --print-sql

Run a query

In [1]: Book.objects.all()
Out[1]: SELECT "book_book"."id", "book_book"."name", "book_book"."author_id" FROM "book_book" LIMIT 21

Execution time: 0.087548s [Database: default]

<QuerySet [<Book: The Stranger>, <Book: Atlas Shrugged>]>

If you don't want to append --print-sql every time, in your django settings, you can set

SHELL_PLUS_PRINT_SQL = True

An alternate way is to enable logging for db queries.

LOGGING = {
    'version': 1,
    'loggers': {
        'django.db.backends': {
            'level': 'DEBUG',
            'handlers': ['console'],
        }
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'filters': ['require_debug_true'],
        }
    },
    'filters': {
        'require_debug_true': {
            '()': 'django.utils.log.RequireDebugTrue',
        }
    },
}

Add this to your settings and restart your shell to see SQL queries.

like image 33
Pandikunta Anand Reddy Avatar answered Sep 24 '22 00:09

Pandikunta Anand Reddy


You can print out the sql for individual queries like so:

your_query = YourModel.objects.all()
print your_query.query

Is that all you need?

like image 37
Sam Dolan Avatar answered Sep 22 '22 00:09

Sam Dolan