Potential Django Bug In QuerySet.query?

Posted by Mike on Stack Overflow See other posts from Stack Overflow or by Mike
Published on 2010-05-28T03:27:36Z Indexed on 2010/05/28 3:31 UTC
Read the original article Hit count: 176

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about python

Related posts about django