Roman Imankulov

Roman Imankulov

Full-stack Python web developer from Porto

search results (esc to close)
21 Dec 2021

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.

I used pygments and sqlparse to make the output of query more developer-friendly.

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.

Formatted and colorized SQL output in the console.

Formatted and colorized SQL output in the console.

Roman Imankulov

Hey, I am Roman, and you can hire me.

I am a full-stack Python web developer who loves helping startups and small teams turn their ideas into products.

More about me and my skills