Last active
May 25, 2017 16:38
-
-
Save slinkp/80f93f168f08a6f92a196702eeb5a777 to your computer and use it in GitHub Desktop.
Print postgres-specific output from django QuerySet w/o evaluating the QuerySet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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