418

How do I get the SQL that Django will use on the database from a QuerySet object? I'm trying to debug some strange behavior, but I'm not sure what queries are going to the database.

2
  • 10
    This isn't a duplicate. the linked question is quite a different topic.
    – craigds
    Mar 23, 2017 at 20:45
  • 2
    @Wooble this isn't a duplicate. It's in the same area as the other question but this question relates to a specific query, not ALL queries.
    – Akrikos
    Aug 22, 2019 at 18:08

5 Answers 5

646

You print the queryset's query attribute.

>>> queryset = MyModel.objects.all()
>>> print(queryset.query)
SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel"
7
  • I found this which mentions it implicitly but nothing that explicitly documents the above Sep 24, 2013 at 22:41
  • 48
    Note that the output of query is not valid SQL, because "Django never actually interpolates the parameters: it sends the query and the parameters separately to the database adapter, which performs the appropriate operations." Source: code.djangoproject.com/ticket/17741
    – gregoltsov
    Jul 7, 2014 at 14:50
  • 2
    Is it possible to see the SQL query before the it is actually executed? I'm getting a database error and want to see what SQL it's trying to execute, but when I run this I simply get a database error and cannot see the full SQL.
    – Ariel
    Jan 5, 2021 at 12:43
  • 1
    If you do anything other than print, you may have to use str(queryset.query), because type(queryset.query) == Query. Aug 4, 2021 at 14:35
  • 4
    To get the valid SQL from Postgres, use this: stackoverflow.com/questions/8112554/…
    – fjsj
    Nov 24, 2021 at 15:00
73

Easy:

print(my_queryset.query)

For example:

from django.contrib.auth.models import User
print(User.objects.filter(last_name__icontains = 'ax').query)

It should also be mentioned that if you have DEBUG = True, then all of your queries are logged, and you can get them by accessing connection.queries:

from django.db import connections
connections['default'].queries

The django debug toolbar project uses this to present the queries on a page in a neat manner.

2
  • 3
    This doesn't always output valid SQL, see the other answers
    – aehlke
    Jul 21, 2014 at 21:12
  • 2
    There is no way to get actual SQL without executing the query first, final SQL is generated by the surrounding RDBMS driver, not Django. The answer is correct as it's the most you can get with Django QuerySet.
    – danius
    Jan 10, 2016 at 7:48
68

The accepted answer did not work for me when using Django 1.4.4. Instead of the raw query, a reference to the Query object was returned: <django.db.models.sql.query.Query object at 0x10a4acd90>.

The following returned the query:

>>> queryset = MyModel.objects.all()
>>> queryset.query.__str__()
7
  • 33
    It probably didn't work because you just typed queryset.query instead of print queryset.query, which calls __str__()
    – hughes
    May 28, 2013 at 17:49
  • 16
    @hughes is right. If you don't want to print it and want it as a string, instead of calling __str__() to get it as a string you should do str(queryset.query).
    – Chad
    May 30, 2013 at 23:31
  • 1
    I am using ipdb to debug and it prints a reference to the query object when I do p queryset. p queryset.__str__() produces the desired result so this is a better answer.
    – Rafay
    Jun 25, 2014 at 5:15
  • 21
    str(queryset.query) would be more pythonic.
    – dbn
    Jul 3, 2014 at 19:34
  • I had this problem on manage.py shell (__str__() did the job)
    – aldux
    Sep 24, 2014 at 21:49
12

This middleware will output every SQL query to your console, with color highlighting and execution time, it's been invaluable for me in optimizing some tricky requests

http://djangosnippets.org/snippets/290/

12

As an alternative to the other answers, django-devserver outputs SQL to the console.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.