> I need to write some custom SQL in Django:
> 
>    from django.db import connection
>    cursor = connection.cursor()
>    cursor.execute("SELECT note FROM journals_journal WHERE LENGTH(note) 
>  > 0 AND note LIKE %s GROUP BY note ORDER BY note;", [q+'%'])
> 
> where q is string, for example 'foo'.

This should be writable in a slightly more Djangoic (I suppose if 
Python code is Pythonic, Django code is Djangoic?  Djanonic? 
Djangonical?  Djangoish?) fashion:

   entries = Journal.objects.filter(note__startswith = q)
   entries = entries.extra(where='length(note) > 0')

(you might have to tweak that "length(note) > 0" bit, as Django 
mungs field-names a bit in the query).

I'm not sure why you're GROUPing BY "note" as you don't have any 
aggregate functions in play in your example code.

http://www.djangoproject.com/documentation/0.95/db-api/#startswith

and the "where" section of

http://www.djangoproject.com/documentation/0.95/db-api/#extra-select-none-where-none-params-none-tables-none

> I have problems with it so I print out connection.queries and I was 
> suprised, because foo% wasn't surrounded by ' or " :
> 
>    SELECT note FROM journals_journal WHERE LENGTH(note) > 0 AND note 
> LIKE foo% GROUP BY note ORDER BY note;'
> 
> Is this normal? Isn't there possibility for SQL inject?

As Malcom noted, it's not quite what was sent to the DB. 
However, it /would/ be nice for debugging purposes to have the 
*exact* query sent to the DB.  However, this would have to be 
supported on a per-backend basis. :(

-tim







--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to