Printing Django Queryset SQL with ""

Getting the SQL from a Django QuerySet

You print the queryset's query attribute.

>>> queryset = MyModel.objects.all()
>>> print(queryset.query)
SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel"

How to see the raw SQL queries Django is running?

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

django.db.connection.queries contains a list of the SQL queries:

from django.db import connection
print(connection.queries)

Querysets also have a query attribute containing the query to be executed:

print(MyModel.objects.filter(name="my name").query)

Note that the output of the query is not valid SQL, because:

"Django never actually interpolates the parameters: it sends the query and the parameters separately to the database adapter, which performs the appropriate operations."

From Django bug report #17741.

Because of that, you should not send query output directly to a database.

If you need to reset the queries to, for example, see how many queries are running in a given period, you can use reset_queries from django.db:

from django.db import reset_queries
from django.db import connection

reset_queries()
# Run your query here
print(connection.queries)
>>> []

Django how to see generated SQL query?

How about using logging?

you can add this in settings.py

LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': True,
},
},
}

and you can add this in your any views.py

import logging

l = logging.getLogger('django.db.backends')
l.setLevel(logging.DEBUG)
l.addHandler(logging.StreamHandler())

In your console, you can check SQL query.

Another way

go shell

python manage.py shell

>>from yourmodel import Example
>>queryset = Example.objects.all()
>>print(queryset.query)

you can see raw query string.

How to print sql query from Django as Debug is False

You can work with Database instrumentation [Django docs] which basically provides a hook for installing wrapper functions around the execution of database queries. Using this you can simply make a wrapper like so:

class QueryLogger:

def __init__(self):
self.queries = []
self.errored = False

def __call__(self, execute, sql, params, many, context):
current_query = {'sql': sql, 'params': params, 'many': many}
try:
result = execute(sql, params, many, context)
except Exception as e:
self.errored = True
current_query['status'] = 'error'
current_query['exception'] = e
raise
else:
current_query['status'] = 'ok'
return result
finally:
self.queries.append(current_query)

Then use it in your view:

from django.db import connection

ql = QueryLogger()

with connection.execute_wrapper(ql), transaction.atomic():
r = Amodel.objects.create(
...
)
Bmodel.objects.filter(id__in=handle_ids_).update(status=4)

if not ql.errored:
for query in ql.queries:
print(query)
else:
print("Some error occured")

How to view corresponding SQL query of the Django ORM's queryset?

Each QuerySet object has a query attribute that you can log or print to stdout for debugging purposes.

qs = Model.objects.filter(name='test')
print(qs.query)

Note that in pdb, using p qs.query will not work as desired, but print(qs.query) will.

If that doesn't work, for old Django versions, try:

print str(qs.query)

Edit

I've also used custom template tags (as outlined in this snippet) to inject the queries in the scope of a single request as HTML comments.

Printing the SQL Query in Django when using a Database Router

Try Model.objects.using('test').all().query.

You can manually select a database with using. See docs.

Update:

Provide just the ENGINE value for DATABSES['default']

Django raises an ImproperlyConfigured exception on every api function when the default database ENGINE is empty. See the docstring here.

How to print Django queryset in Tabular form in python3 manage.py shell

Django doesn't have this feature, but it would be easy to create a function using tabulate

from tabulate import tabulate

def output_table(queryset, limit=50):
headers = [x.name for x in queryset.model._meta.fields]
rows = queryset.values_list(*headers)
if limit is not None:
rows = rows[:limit]
print(tabulate(rows, headers))


Related Topics



Leave a reply



Submit