Bootstrap FreeKB - Flask - Loop through SQLAlchemy results
Flask - Loop through SQLAlchemy results

Updated:   |  Flask articles

If you are not familiar with SQLAlchemy, check out my article Getting Started with SQLAlchemy.

This assumes you have already setup Flask to connect to a database.

Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.

  • Model -> models.py
  • View -> views.py
  • Controller -> __init__.py

And let's say your Flask app has the following structure.

├── main.py
├── my-project (directory)
│   ├── __init__.py
│   ├── views.py
│   ├── models.py
│   ├── templates (directory)
│   │   ├── base.html
│   │   ├── home.html
│   │   ├── results.html

 

Let's say models.py contains the following. In this example, the name of the table is "users".

from . import db

class users(db.Model):
  id        = db.Column(db.Integer, nullable=False, unique=True, primary_key=True)
  firstname = db.Column(db.String(20), nullable=False, unique=True)
  lastname  = db.Column(db.String(40), nullable=False, unique=False)

 

Here is how you could query all of the data from a table where "users" is the name of the table in your model and loop through the results in Python.

from .models import users

@views.route('/Results', methods=['GET', 'POST'])
def Results():

    results = users.query.all()

    for row in results:
        print(f"ID         = {row.id}")
        print(f"first name = {row.firstname}")
        print(f"last name  = {row.lastname}")

    return render_template('results.html', results=results)  

 

In the blueprint / route above, render_template includes results=results, where "results" contains the results of the query. Then your HTML could look something like this, where you loop through the results in HTML / Jinja.

{% extends "base.html" %}
{% block content %}
{% if results == None %}
    no results
{% else %}
    {% for row in results %}
        First Name = {{ row['firstname'] }}
        Last Name  = {{ row['lastname'] }}
    {% endfor %}
{% endif %}
{% endblock %}

 

Be aware that if you use one() to result one result . . . 

result = users.query.filter_by(email='john.doe@example').one()

 

Or use first() to only return the first result . . .

result = users.query.filter_by(email='john.doe@example').first()

 

Then you cannot loop over the results, since only a single result would be returned. However, you can still get the result data, like this.

from .models import users

@views.route('/Results', methods=['GET', 'POST'])
def Results():

    result = users.query.filter_by(email='john.doe@example').first()

    print(f"ID         = {row.id}")
    print(f"first name = {row.firstname}")
    print(f"last name  = {row.lastname}")

    return render_template('results.html', results=result)  

 

Or like this, in your HTML / Jinja.

{% extends "base.html" %}
{% block content %}
{% if result == None %}
    no results
{% else %}
    First Name = {{ result['firstname'] }}
    Last Name  = {{ result['lastname'] }}
{% endif %}
{% endblock %}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter adf64b in the box below so that we can be sure you are a human.