Search code examples
pythonsqlalchemy

query using sqlalchemy returned zero rows


I've a python file, where I read a table. If no records are returned I want msg 'No matching recs found' to be displayed else the data to be displayed. DB is Postgres and python file reads table book. My current code as below doesn't give the desired results. Please, if someone can help about this.

app.py file:

from flask import Flask, render_template
from sqlalchemy import create_engine
from sqlalchemy.sql import text
from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine("postgresql://postgres:admin@localhost:5432/catalog_db")
db = scoped_session(sessionmaker(bind=engine))

app = Flask(__name__)

app.secret_key = '12345678'
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"

@app.route('/bookList')
def booklist():
    statement = text("""SELECT title,author FROM book order by id""")
    books = db.execute(statement)

    return render_template("BookList.html", books=books)

if __name__ == '__main__':
    app.run(debug=True)

BookList.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Result</title>
</head>
<body>
  <table class="table">
    <thead>
      <tr>
        <th scope="col">Title</th>
        <th scope="col">Author</th>
      </tr>
    </thead>
      {% if books == None %}
          <p>No Matching records found</p>
      {% else %}
          {% for book in books %}
              <tr>
                  <td>{{book.title}}</td>
                  <td>{{book.author}}</td>
              </tr>
          {% endfor %}
      {% endif %}
  </table>
</body>
</html>

Solution

  • You can remove the if and use Jinja's for else:

    {% for book in books %}
      <tr>
        <td>{{book.title}}</td>
        <td>{{book.author}}</td>
      </tr>
    {% else %}
      <tr>
        <td colspan="2">No matching records found.</td>
      </tr>
    {% endfor %}
    

    The else block will show up "if no iteration took place because the sequence was empty" (reference).