Take AVG from SQL Table AND Display in HTML

Viewed 26

I looked up this answer in numerous forums and none seem to solve my problem. I am looking for a bit of help.

I want to take the average of numbers in a SQL database and display the average in HTML. I am using Flask, Python, SQL, and HTML.

Here is my PYTHON code:

avg_hours = db.execute("SELECT CAST(AVG(hours) AS int) FROM pain WHERE user_id = ?", user_id)

My HTML code:

      {% for row in avg_hours %}
         <h4>Average Hours: {{ row }}   </h4>
       {% endfor %}

But it displays like this on the html page:

Average Hours: {'CAST(AVG(hours) AS int)': 11}

How do I get it to display just the number? I want the display to show

Average Hours : 11

Any help would be appreciated

1 Answers

I figured it out. Here is the solution for others who may run into the problem:

Python Code:

@app.route("/")
@login_required
def index():
    """Show portfolio"""
    user_id = session["user_id"]

    #average of numbers in the column hours from the table pain for user
    avg_hours = db.execute("SELECT AVG(hours) AS average FROM pain WHERE user_id = ?", user_id)

    #i is the row in the avg_hours database
    for i in avg_hours:
       #create a variable for the average
       average1 = i["average"]
       #create new variable to convert value into an integer 
       average2 = int(average1)

 #render template to display value on html page
 return render_template("index.html", average=average2)

Simple HTML Code:

     <h4>Average Hours: {{ average }}   </h4>
Related