Inserting literal % sign in QuerySet.extra()

60 views
Skip to first unread message

Gergely Polonkai

unread,
Mar 27, 2015, 5:38:15 PM3/27/15
to django...@googlegroups.com

Hello,

I’d like to execute the following code:

Booking.objects.filter(start_ts__isnull = False, end_ts__isnull = False).extra(select = {'amount': "strftime('%s', end_ts) - strftime('%s', start_ts)"})

However, in the shell, I get the following error:

Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/polesz/Projects/duckbook/venv/lib/python3.4/site-packages/django/db/models/query.py", line 835, in extra clone.query.add_extra(select, select_params, where, params, tables, order_by) File "/home/polesz/Projects/duckbook/venv/lib/python3.4/site-packages/django/db/models/sql/query.py", line 1744, in add_extra entry_params.append(next(param_iter)) StopIteration

I have tried doubling the percent signs (%%s) and escaping them with a backslash (\%s), but neither helped. I also looked at this answer[1], but that solution doesn’t work with QuerySet.extra() (or I just miss the point).

What is the correct way to solve this?

I also tried to use select_params like this:

Booking.objects.filter(start_ts__isnull = False, end_ts__isnull = False).extra(select = {'amount': "strftime('%s', end_ts) - strftime(%s, start_ts)"}, select_params = ['%s', '%s'])

but regardless the usage of quote signs, the resulting query has \'%s\', which gives an SQL error, of course.

Best,
Gergely

[1] http://stackoverflow.com/a/18143147/1305139

Tim Graham

unread,
Mar 27, 2015, 9:15:55 PM3/27/15
to django...@googlegroups.com
This is fixed in Django 1.8. See the fifth item in https://docs.djangoproject.com/en/dev/releases/1.8/#models.

Gergely Polonkai

unread,
Mar 28, 2015, 2:49:21 AM3/28/15
to django...@googlegroups.com

Great, thank you!

Although I'm more than willing to upgrade, I still wonder if this fix will be backported to 1.7…

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/fa509ee1-6bb2-43c8-a1a1-e12ad70a123f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Tim Graham

unread,
Mar 29, 2015, 12:13:29 PM3/29/15
to django...@googlegroups.com
No, it won't. See https://docs.djangoproject.com/en/dev/internals/release-process/#supported-versions for the guidelines on which changes are backported.
Reply all
Reply to author
Forward
0 new messages