I'm doing a small App with Flask and MySQL. I'm trying to show certain items in a table, but I would like to filter these items based on only 1 field of the database.
This example is doing what I need, but only if my list has 2 items. And the idea is that I could use it with "n" items:
@app.route('/search2', methods=['GET', 'POST'])
def search2():
if request.method == 'POST':
contents= request.form['referencias']
list_values = contents.split(" ")
cursor.execute("SELECT * from ref_stocks WHERE Ref_Prod IN (%s,%s)", (list_values[0],list_values[1]))
conn.commit()
data = cursor.fetchall()
return render_template('search2.html', data=data)
return render_template('search2.html')
Finally I found a way. Maybe it could help other people with same problem:
def convert(lista_ref):
return tuple(i for i in lista_ref)
def search2():
if request.method == 'POST':
contents= request.form['referencias']
# convert to list
list_values = contents.split(" ")
# Items in list
number_list= len(list_values)
# convert to tuple
lista_ref = list_values
lista_nueva = convert(lista_ref)
#concatenating values
art = ("%s," * number_list)[:-1]
where_in = "(" + art + ")"
cursor.execute("SELECT * from ref_stocks WHERE PrimeroDeRef_Prod IN " + where_in, lista_nueva)
conn.commit()
data = cursor.fetchall()
return render_template('search2.html', data=data)
return render_template('search2.html')