Potential Django Error In QuerySet.query?

Disclaimer: I'm still learning Django, so I might be missing something, but I don’t understand what it will be ...

I am 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 ) >>> 

Note that it does not put quotation marks around "a" or "b"! Now I decided that the request is running in order. So in reality this should be so. But, it is rather annoying that the listing of the request does not print correctly. 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 corrupted SQL code, but also has the seeds of an SQL injection attack. Now, obviously, this would not actually work for a number of reasons (1. The syntax is all wrong, deliberately show Django's odd behavior. 2. Django will not actually execute such a request, it will actually put quotes and slashes and that's it that there, as intended).

But it really makes debugging confusing, and it makes me wonder if something is wrong with my Django installation.

Is this happening for you? If so / no, what is your version of Python and Django?

Any thoughts?

+7
python django
source share
1 answer

Ok, I just figured it out. It's not a mistake. View source 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 is working fine. :)

+9
source share

All Articles