开发者

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

开发者 https://www.devze.com 2023-02-05 20:08 出处:网络
I know that you can output the SQL to see tables that are created. Is it possible for Django to out开发者_StackOverflowput the sql used for any query like:

I know that you can output the SQL to see tables that are created. Is it possible for Django to out开发者_StackOverflowput 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.


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)


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/


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消