Skip to content

Instantly share code, notes, and snippets.

@slinkp
Last active May 25, 2017 16:38
Show Gist options
  • Save slinkp/80f93f168f08a6f92a196702eeb5a777 to your computer and use it in GitHub Desktop.
Save slinkp/80f93f168f08a6f92a196702eeb5a777 to your computer and use it in GitHub Desktop.
Print postgres-specific output from django QuerySet w/o evaluating the QuerySet
from django.db import connection
def queryset_to_postgres(qs):
"""
Given a `QuerySet`, return a correctly formatted (but not pretty-printed) sql string that can be run
on postgres.
For debugging only, as `cursor.mogrify` is specific to psycopg2, not part of python db api.
Needed because the usual `str(qs.query)` gives generic sql that may not execute correctly on postgres,
eg. case-sensitive names may not be cased correctly.
Credit: https://stackoverflow.com/a/22828674/137635
"""
sql, params = qs.query.sql_with_params()
cursor = connection.cursor()
sql = cursor.mogrify(sql, params)
return sql
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment