Disclaimer: I'm still learning Django, so I might be missing something here, but I can't see what it would be...
I'm running Python 2.6.1 and Django 1.2.1.
(InteractiveConsole)
>>> from myproject.myapp.models import *
>>> qs = Identifier.objects.filter(Q(key="a") | Q(key="b"))
>>> print qs.query
SELECT `app_identifier`.`id`, `app_identifier`.`user_id`,
`app_identifier`.`key`, `app_identifier`.`value` FROM
`app_identifier` WHERE (`app_identifier`.`key` = a OR
`app_identifier`.`key` = b )
>>>
Notice that it doesn't put quotes around "a" or "b"! Now, I've determined that the query executes fine. So, in reality, it must be doing so. But, it's pretty annoying that printing out the query prints it wrong. Especially if I did something like this...
>>> qs = Identifier.objects.filter(Q(key=") AND") | Q(key="\"x\"); DROP TABLE
`app_identifier`"))
>>> print qs.query
SELECT `app_identifier`.`id`, `app_identifier`.`user_id`,
`app_identifier`.`key`, `app_identifier`.`value` FROM
`app_identifier` WHERE (`app_identifier`.`key` = ) AND OR
`app_identifier`.`key` = "x"); DROP TABLE `app_identifier` )
>>>
Which, as you can see, not only creates completely malformed SQL code, but also has the seeds of a SQL injection attack. Now, obviously this wouldn't actually work, for quite a number of reasons (1. The syntax is all wrong, intentionally, to show the oddity of Django's behavior. 2. Django won't actually execute the query like this, it will actually put quotes and slashes and all that in there like it's supposed to).
But, this really makes debugging confusing, and it makes me wonder if something's gone wrong with my Django installation.
Does this happen for you? If so/not, what version of Python and Django do you have?
Any thoughts?
Ok, I just figured it out. It's not a bug. Browsing the source of django/db/models/sql/query.py:
160 def __str__(self):
161 """
162 Returns the query as a string of SQL with the parameter values
163 substituted in.
164
165 Parameter values won't necessarily be quoted correctly, since that is
166 done by the database interface at execution time.
167 """
168 sql, params = self.get_compiler(DEFAULT_DB_ALIAS).as_sql()
169 return sql % params
(http://code.djangoproject.com/browser/django/trunk/django/db/models/sql/query.py)
Everything's working properly. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With