Bootstrap FreeKB - Flask - Count records in a table using SQLAlchemy
Flask - Count records in a table using SQLAlchemy

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)

 

Your HTML page would have an input form like this. Notice in this example that the name of the input is SearchString.

<form method="post" action="/Results">
  <input type="text" placeholder="search . . ." name="SearchString">
</form>

 

Here is how you could count the results using an equals query.

from flask import Blueprint, render_template, request
from datetime import datetime
from . import app_obj, db, get_db_connection
from .models import users

views = Blueprint('views', __name__)

@views.context_processor
def inject_now():
    return {'now': datetime.utcnow()}

@views.route('/')
def home():
    return render_template('home.html')

@views.route('/Results', methods=['GET', 'POST'])
def results():
    id = request.form.get('id')
    count = users.query.filter_by(id=id).count()
    print(f"count = {count}")

    return render_template('results.html')  

 

Or like this, by first doint the query with the count() function and then applying the count() function to the results.

data = users.query.filter_by(id=id)
count = data.count()

 

Here is how you could count the results using a Case SenSiTiVe LIKE query.

@views.route('/Results')
def results():
    SearchString = request.form["SearchString"]
    search = "%{}%".format(SearchString)
    count = users.query.filter(users.username.like(search)).count()
    print(f"count = {count}")

    return render_template('results.html')  

 

Here is how you could count the results using ilike (not Case InSenSiTiVe) query.

@views.route('/Results')
def results():
    SearchString = request.form["SearchString"]
    search = "%{}%".format(SearchString)
    count = users.query.filter(users.username.ilike(search)).count()
    print(f"count = {count}")

    return render_template('results.html')  

 

Here is how you could count two (or more) queries.

@views.route('/Results')
def results():
    count = users.query.filter(users.firstname.like(request.form.get('firstname'))).filter(users.firstname.like(request.form.get('lastname'))).count()
    print(f"count = {count}")

    return render_template('results.html')  



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 1e01af in the box below so that we can be sure you are a human.