The Python Oracle

Getting the SQL from a Django QuerySet

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Intrigue Looping

--

Chapters
00:00 Getting The Sql From A Django Queryset
00:21 Accepted Answer Score 652
00:37 Answer 2 Score 73
01:14 Answer 3 Score 69
01:36 Answer 4 Score 12
01:56 Answer 5 Score 12
02:09 Thank you

--

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

--

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.