Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Django's ORM output the SQL query it is using?

I know that you can output the SQL to see tables that are created. Is it possible for Django to output the sql used for any query like:

Protocols.objects.filter(active=False)

? I couldn't find this in the docs, so hopefully someone can point them to me, if in fact Django can do this.

like image 865
Randy Avatar asked Jan 21 '11 18:01

Randy


3 Answers

See Django FAQ: How can I see the raw SQL queries Django is running?:

>>> from django.db import connection    
>>> connection.queries = []
>>> Protocols.objects.filter(active=False)
>>> print connection.queries
like image 60
Tomasz Zieliński Avatar answered Oct 12 '22 14:10

Tomasz Zieliński


Yes it can. You need to make sure that you have DEBUG=True in your settings file

you can see what sql queries have been executed by...

>>> from django.db import connection
>>> connection.queries

You obviously need to have executed some queries to see them here.

To see what is executed to deliver a particular QuerySet you can do the following

str(MyModel.objects.filter(myvar__gte=15).query)

It's documented here http://docs.djangoproject.com/en/dev/faq/models/

like image 39
Dan Avatar answered Oct 12 '22 13:10

Dan


I find the Django debug toolbar to be invaluable. There's also .as_sql() for in-code display of things (see this SO post for a note that's a good line in to it)

like image 30
Steve Jalim Avatar answered Oct 12 '22 13:10

Steve Jalim