viewing generated SQL without running the query

85 views
Skip to first unread message

Gary Wilson

unread,
Aug 28, 2006, 11:53:53 PM8/28/06
to Django users
I see that there is a _get_sql_clause() method, but is there a function
that will return the constructed query string?

DavidA

unread,
Aug 29, 2006, 9:13:32 AM8/29/06
to Django users

Gary Wilson wrote:
> I see that there is a _get_sql_clause() method, but is there a function
> that will return the constructed query string?

You can just do the same construction that's done in
django/db/models/query.py:

>>> from danet.blog.models import Post, Tag
>>> qs = Tag.objects.filter(title__icontains='a', description__icontains='n')
>>> cols, sql, args = qs._get_sql_clause()
>>> "SELECT %s %s" % (', '.join(cols), sql % tuple(args))
'SELECT `blog_tag`.`slug`, `blog_tag`.`title`, `blog_tag`.`description`
FROM `b
log_tag` WHERE (`blog_tag`.`description` LIKE %n% AND
`blog_tag`.`title` LIKE %a
%) ORDER BY `blog_tag`.`title` ASC'
>>>

There's some special handling for DISTINCT if you look at
django.db.models.query.iterator(), but the snippet above is close
enough. After a while you get used to just looking at the list from
_get_sql_clause() directly and can just add the "SELECT" and replace
the args in your head.
-Dave

Malcolm Tredinnick

unread,
Aug 29, 2006, 2:49:36 PM8/29/06
to django...@googlegroups.com
On Tue, 2006-08-29 at 03:53 +0000, Gary Wilson wrote:
> I see that there is a _get_sql_clause() method, but is there a function
> that will return the constructed query string?

Deja vu. I tried to implement something like this a little while back.
The thing that is hard about getting it to work is that we rely on the
database backend to do some of the quoting and function substitution for
us. As far as I know, there's no generic way to pull that information
out of each backend. I wasn't really keen in duplicating the logic from
the queryset stuff, however this may be easier with the query.py rewrite
I'm doing (I just thought of that point now, so I really mean "may" --
need to look into it).

Regards,
Malcolm

Gary Wilson

unread,
Aug 30, 2006, 12:12:15 AM8/30/06
to Django users

Ah, I guess I didn't notice the using of the db backend to do some work
for us. That does make things a bit harder.

Reply all
Reply to author
Forward
0 new messages