views:

64

answers:

1

I know that you can get the SQL of a given QuerySet using

print query.query

but as we know from a previous question ( http://stackoverflow.com/questions/2926483/potential-django-bug-in-queryset-query ) the returned SQL is not properly quoted. See http://code.djangoproject.com/browser/django/trunk/django/db/models/sql/query.py

Is there any way that is it possible to get the raw, executable SQL (quoted) for a given QuerySet without actually executing it?

+2  A: 

Django never creates the raw sql, so no. To prevent SQL injection, django passes the parameters separately to the database drivers at the last step. The best way to get the actual SQL is to look at your query log, which you cannot do before you execute the query.

Mike Axiak
So the answer is no. Thanks.
epoch
@Mike: +1. @epoch: Correct, the answer is no. If you are curious to see the query as it passed to the backend, you can use the following snippet. `from django.db import DEFAULT_DB_ALIAS; queryset.query.get_compiler(DEFAULT_DB_ALIAS).as_sql()`
Manoj Govindan
And if you really want to live life on the dangerous side, you could do this: `sql, params = queryset.query.get_compiler(DEFAULT_DB_ALIAS).as_sql();``sql = sql % tuple(["'%s'" % (param) for param in params])`
epoch
I don't really see the problem with `__str__` when querying a PostgreSQL database when doing `Something.objects.all().query`?
Deniz Dogan
But there is a problem when querying a development database (sqlite).
epoch