pythonsqllistflaskfetchall

(Flask) How to modify list after a fetchall


(sorry for my very bad english !... ^^) Hello everyone

I make a def in my flask to keep with my fetchall a list. But i need to add a parameters in my list to do something. I need to add in list[4]

However, i don't know how i can do this ...

# Fonction récupération des comptes patients
def get_accountpatient():
    var = "SELECT id, Nom, Prenom, Tel FROM `users` WHERE Privilege = 'patient'"
    try:
        cur = bdd_login()
    except pymysql.Error as e:
        return session_out(e)
    cur.execute(var)
    list = cur.fetchall()
    cur.close()
    print(list)
    return list

list return : ((1, 'BLOQUIAU', 'Thomas', '0669696969'), (2, 'PARAT', 'Clement', '0669696969'), (24, 'Gerez', 'Quentin', '0642181185'))

Python code in another fonction to call get_accountpatient()

return render_template('user_manage.html', **templateData, accounts=get_accountpatient(), sidebar=7, usermanage_div=2)

HTML code

<thead>
  <tr>
    <th>ID</th>
    <th>Nom</th>
    <th>Prénom</th>
    <th>Téléphone</th>
    <th>Administré par {{prenom_user}} {{name_user}}</th>
  </tr>
</thead>
<tbody>
  {% for list in accounts %}
    <tr>
        <td>{{ list[0] }}</td>
        <td>{{ list[1] }}</td>
        <td>{{ list[2] }}</td>
        <td>{{ list[3] }}</td>
        <td>{{ list[4] - **I NEED TO ADD THIS LINE** }}</td>
    </tr>
  {% endfor %}
</tbody>

I want this it's possible

((1, 'BLOQUIAU', 'Thomas', '0669696969', 'Oui'), (2, 'PARAT', 'Clement', '0669696969', 'Oui'), (24, 'Gerez', 'Quentin', '0642181185', 'Oui'))

Best regards


Solution

  • The most efficient way is to add the constant value in the SQL query:

    sql = """SELECT id, Nom, Prenom, Tel, 'Oui' As Admin 
             FROM `users` WHERE Privilege = 'patient'
          """
    ...
    cur.execute(sql)
    

    Should you need the value to be dynamic, pass it as a parameter. Below assumes your DB-API uses %s for param placeholders (others may use qmarks ?):

    sql = """SELECT id, Nom, Prenom, Tel, %s As Admin 
             FROM `users` WHERE Privilege = 'patient'
          """
    ...
    myvar = 'Oui'
    cur.execute(sql, (myvar,))    # PARAMS MUST BE PASSED IN TUPLE OR LIST (NOT SINGLE VALUES)