How to pretty print SQL from Django
Often, I find myself experimenting in the Django console with ad-hoc model queries.
Where it’s not clear how Django turns a queryset to SQL, I find it helpful to print the resulting query. Django QuerySet object has a
query attribute. However, its format would benefit from extra formatting.
pip install pygments sqlparse
The snippet itself is very straightforward.
# file sql_utils/utils.py from pygments import highlight from pygments.formatters import TerminalFormatter from pygments.lexers import PostgresLexer from sqlparse import format from django.db.models import QuerySet def print_sql(queryset: QuerySet): formatted = format(str(queryset.query), reindent=True) print(highlight(formatted, PostgresLexer(), TerminalFormatter()))
This is how it looks like on the screenshot.