0

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')

1 Answers1

0

Here you go if you need to filter by one field

 cursor.execute("SELECT * from ref_stocks WHERE Ref_Prod IN (%s)",(list_values[0]))
otejiri
  • 1,017
  • 6
  • 20
  • Thanks Teijiri! Unfortunately, I trying to find a flexible way where I could filter by one, by two, by three, by x items... depending of the number of items that I could have in my list... – karvis6974 May 01 '20 at 16:06