0

I am trying to know the

1) time taken or duration and
2) raw sql

for any django model queryset

Eg:

users = User.objects.all()
print(time_take for users)
print(raw sql of users)

Answer tried from going through some previous solutions on this questions in Stack

sql:

I thinking to use the below as answer for sql query. It is given by @Flash in https://stackoverflow.com/a/47542953/2897115

from django.db import connections
def str_query(qs):
    """
    qs.query returns something that isn't valid SQL, this returns the actual
    valid SQL that's executed: https://code.djangoproject.com/ticket/17741
    """
    cursor = connections[qs.db].cursor()
    query, params = qs.query.sql_with_params()
    cursor.execute('EXPLAIN ' + query, params)
    res = str(cursor.db.ops.last_executed_query(cursor, query, params))
    assert res.startswith('EXPLAIN ')
    return res[len('EXPLAIN '):]

timetaken:

And for timetaken i use start = time() and stop = time()

the code becomes:

someview()     
     start = time()
     qs = Somemodels.objecsts.all()
     stop = time()
     sql = str_query(qs)
     timetaken = "%.3f" % (stop - start)
     ...

Q Will this show the correct values of sql and timetaken.

Q Is there any way to know the timetaken from the cursor.db module instead of using start = time() and stop = time()

I also found someplace to get sql using:

from django import db
db.connection.queries[-1]

Q How is this different from str_query(qs) method i am trying to use

Santhosh
  • 9,965
  • 20
  • 103
  • 243
  • 1
    There are several questions similar to this already, which provide approaches to do this. See https://stackoverflow.com/questions/1074212/how-can-i-see-the-raw-sql-queries-django-is-running?rq=1 for example – solarissmoke Aug 11 '19 at 04:51
  • Can you see my edited question with answer tried from the link you provided – Santhosh Aug 11 '19 at 10:51

0 Answers0