I have an endpoint where I’m passing in an array of ints thus:
I get it out of my endpoint request and turn it into a string like this.
list_of_ids = request.data['list_of_ids']
list_of_ids = "','".join(str(e) for e in list_of_ids)
It looks like this in debug mode, even though it prints out looking fine.
'7690\',\'10964\',\'10973\',\'10977\',\'10960\',\'10958\',\'10961\',\'10571'
I then try to punch it into my SQL statement like this (see “list_of_ids” below in the cursor.execute()):
# This is a custom query, no Django Models involved
query = f"""
UPDATE staffing_change_report
{set_string}
WHERE payroll_code IN (%s)
AND business_process_type IN ('Hire', 'Contract Contingent Worker');
"""
try:
with connection.cursor() as cursor:
cursor.execute(query, [boolean_to_set, boolean_to_set, list_of_ids])
But the query fails without errors and when I grab it from the cursor in debug mode it looks like this with the escape characters all in place:
UPDATE staffing_change_report
SET hire_process_is_completed = 0, hire_init_process_is_completed = 0
WHERE payroll_code IN ('7690\',\'10964\',\'10973\',\'10977\',\'10960\',\'10958\',\'10961\',\'10571')
AND business_process_type IN ('Hire', 'Contract Contingent Worker');
I assume (but don’t know for sure) that the presence of those escape characters in the cursor’s copy of the SQL statement is the reason the query is not working right. I wonder if, because this call is also supposed to “sanitize” the inputs, the library is somehow refusing to handle the python string as expected?
I’ve tried everything I can think of to “clear” those escape characters, but I believe this is a feature of Python…? In other words, there’s no way to avoid the escape character of “\” if you have quotations in your string…
Is there a way to make this work? If I hardcode the “IN()” in the SQL, it works fine, but I cannot find a way to pass in a string or a list or a tuple that works with cursor.execute.
By the way, this is the cursor from: from django.db import connection
PS. I did find this, which does work:
for value in my_tuple:
cursor.execute(query, [boolean_to_set, boolean_to_set, value])
And I’ll live with it if I have to, but this turns a query with N number of items in the IN() clause into N number of queries - something that does NOT scale well…
Thanks in advance!