Correctly passing parameters to raw query

103 views
Skip to first unread message

termopro

unread,
Sep 24, 2014, 4:34:15 PM9/24/14
to django...@googlegroups.com
Hello,

I am constructing raw query which looks like the following:
"SELECT * FROM some_table  WHERE id IN (1,3,5);"

So inside my view i write:
entities = Entity.objects.raw("""
SELECT * FROM some_table  WHERE id IN (%s);
""", [ids_list])

How should i correctly pass the argument ? Because i keep getting errors no matter how i try.


p.s. - In reality my query is much more complex, i have simplified it just to explain the question

Collin Anderson

unread,
Sep 24, 2014, 5:37:16 PM9/24/14
to django...@googlegroups.com
Interesting. I don't use raw queries, but I wonder if Django doesn't support lists as parameters to raw()

James Brewer

unread,
Sep 24, 2014, 6:55:15 PM9/24/14
to django...@googlegroups.com
This is going to depend on the version of Django you're using. Accord to the docs for 1.7[1], this should work fine. 

After playing around in the shell for a bit, I found I was getting an error complaining about arguments not being converted during string formatting. It seems the problem occurs when a `RawQuerySet` object is stringified. This line[2] converts the the params into a tuple if the `params` object is not a dictionary. For some reason, when this tuple is used in string formatting, everything breaks.

I haven't been able to figure out a solution and, frankly, I don't even know if this is the error you're getting. We really do need more solution.

If anyone else can shed some light on the issue I've raised, that would be fantastic. If not, I will submit a bug report.


On Wed, Sep 24, 2014 at 2:37 PM, Collin Anderson <cmawe...@gmail.com> wrote:
Interesting. I don't use raw queries, but I wonder if Django doesn't support lists as parameters to raw()

--
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/a117b2f7-2ff4-4fe9-8c56-9d5e137acd58%40googlegroups.com.

For more options, visit https://groups.google.com/d/optout.



--
James Brewer

James Brewer

unread,
Sep 24, 2014, 6:57:42 PM9/24/14
to django...@googlegroups.com
Also, it is worth mentioning that the RawQuerySet object looks to have been refactored in the latest development release. I have not verified this issue on the development branch.
--
James Brewer
Reply all
Reply to author
Forward
0 new messages