The Python Oracle

Getting the SQL from a Django QuerySet

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping

--

Chapters
00:00 Question
00:27 Accepted answer (Score 623)
00:43 Answer 2 (Score 68)
01:20 Answer 3 (Score 66)
01:49 Answer 4 (Score 12)
02:04 Thank you

--

Full question
https://stackoverflow.com/questions/3748...

Answer 1 links:
[django debug toolbar]: https://github.com/jazzband/django-debug...

Answer 2 links:
[The accepted answer]: https://stackoverflow.com/a/3748307/

Answer 3 links:
[django-devserver]: https://github.com/dcramer/django-devser...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #sql #django #djangoqueryset

#avk47



ACCEPTED ANSWER

Score 655


You print the queryset's query attribute.

>>> queryset = MyModel.objects.all()
>>> print(queryset.query)
SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel"



ANSWER 2

Score 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.




ANSWER 3

Score 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/




ANSWER 4

Score 12


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