How to pass variadic parameters for “IN clause”… here is a solution to the problem.
How to pass variadic parameters for “IN clause”
I am preparing the following session.execute statement.
I have very few conditions, only one IN clause. I get the following error.
I know I made a mistake but couldn’t get it to work.
filter_site_value = ['Filter 1', 'Filter 2'].
session = get_session()
query = 'SELECT * FROM table where cv = %s AND dt > %s and dt < %s AND st IN (%s)' % ','.join('%s' for i in filter_site_value)
data = (filter_customer_value,filter_date_start_value, filter_date_end_value, filter_site_value)
rows = session.execute(query, data)
“Error Type”
: “Type Error”,
“errorMessage”: “Insufficient format string arguments”
Please help.
Solution
There are 3 places in your string where you need to format a value (%s), you only need to provide a value: ‘,'.join('%s' for i in filter_site_value).
If you have:
x = string_to_format % values
And string_to_format contains X number of %s
(or %d %r ...),
then you need the X value/p> in values
See:
https://docs.python.org/2/library/string.html , https://pyformat.info/
What you might want to do is:
query = 'SELECT * FROM table where cv = %s AND dt > %s and dt < %s AND st IN ('+ ','.join(filter_site_value)+')'
data = (filter_customer_value,filter_date_start_value, filter_date_end_value)
or
query = 'SELECT * FROM table where cv = %s AND dt > %s and dt < %s AND st IN ('+ ','.join(%s for i in filter_site_value)+')'
data = (filter_customer_value,filter_date_start_value, filter_date_end_value)+tuple(filter_site_value)