On Wed, May 13, 2009 at 5:53 AM, Daniel Roseman <
roseman.dan...@googlemail.com> wrote:

>
> On May 13, 2:25 am, Thierry <lamthie...@gmail.com> wrote:
> > My table has the following entry:
> >
> > id      name
> > 1       foo's
> >
> > I'm currently trying the following:
> >
> > value = "foo's"
> >
> > MyModel.objects.get(name = value)
> >
> > The above is raising the exception DoesNotExist.  Doesn't the get
> > function automatically escape the single quote?  Is there also a way
> > to output the generated SQL of the above method?
>
> No, there's no 'escaping' for database lookups. Are you sure the
> element actually exists in the DB?
>

I'm confused by your answer because your first sentence here seems to
conflict with the second.

The single quote in the name will be automatically escaped, if necessary.
Whether it's necessary I believe will depend on how the database backend
does quoting.  I'm most familiar with MySQL, where the "foo's" value will be
quoted using single quotes, so the embedded single quote will need to be
escaped, and that will be done automatically.


>
> You can see the code (as long as DEBUG=True) by doing:
> from django.db import connection
> connection.queries


True, but note that what is logged in connection.queries is the SQL before
being handed to the backend for quoting.  So for a question like this one,
what's logged in connection.queries may give the wrong answer.  For example,
this shell session gives the impression that the foo's value is not quoted:

>>> from ttt.models import FCollection
>>> from django.db import connection
>>> value = "foo's"
>>> FCollection.objects.get(name=value)
<FCollection: foo's>
>>> connection.queries[-1]
{'time': '0.001', 'sql': u"SELECT `ttt_fcollection`.`id`,
`ttt_fcollection`.`name` FROM `ttt_fcollection` WHERE
`ttt_fcollection`.`name` = foo's "}
>>> quit()

However, if you have logging turned on for MySQL and look at its log, you
can see that in fact the value foo's was enclosed in single quotes and the
embedded single quote correctly escaped when the query was actually sent to
the database:

176 Query       SELECT `ttt_fcollection`.`id`, `ttt_fcollection`.`name` FROM
`ttt_fcollection` WHERE  `ttt_fcollection`.`name` = 'foo\'s'

connection.queries is usually sufficient, but the database log is the most
accurate way I know of to see exactly what SQL was sent to the database.

Karen

--~--~---------~--~----~------------~-------~--~----~
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 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to