Look at the sql statements executed by django and two ways to consume time

  • 2020-09-28 08:59:52
  • OfStack

Here are two ways to view sql statements executed by django.

Method 1:


queryset = Apple.objects.all()
print queryset.query

SELECT `id`, `name` FROM `apple`

This method can only view the select statement, but cannot view other updated saved statements, and it will report an error.

That means that only Queryset has the query method. Now let's look at method 2.

Method 2:


from django.db import connection

print connection.queries
[{u'time': u'0.098', u'sql': u'SELECT `app_detail`.`app_id` FROM `app_detail` WHERE `app_detail`.`id` = 20 '}]

It prints all executed sql statements and the elapsed time, which is very useful.

If you have more than one database, you can select the database using the following methods:


from django.db import connections

c = connections['Fruits']
print c.queries

Select connect to 'Fruits' database and print the associated sql statement.


Related articles: