Retrieval

In this lesson, we will discover how to retrieve objects from the database using the "query" object of the model class.

In the previous lesson, we inserted elements in the database by creating objects of the models. In this lesson, we will retrieve these objects from the database using the SQLAlchemy ORM.

Common methods of retrieval in the query object #

The query object is a member variable of the Model class. This object provides us with a method to execute the SELECT statement of SQL. We can find details on all the methods that can be used on this object in the SQLAlchemy docs.

query.all() #

This method will retrieve all entries of the Model class on which it is called. A demonstration is given below.

Press + to interact
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class User(db.Model):
email = db.Column(db.String, primary_key=True, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
db.create_all()
archie = User(email = "archie.andrews@email.com", password = "football4life")
veronica = User(email = "veronica.lodge@email.com", password = "fashiondiva")
db.session.add(archie)
db.session.add(veronica)
try:
db.session.commit()
except Exception as e:
db.session.rollback()
print(User.query.all())

Explanation #

  • In lines 14 - 22, we have performed the steps for insertion in the database (as explained in the previous lesson).
  • Then, in line 24, we have called the query.all() function on the User model class.
  • We can observe that all the objects we inserted have been retrieved and printed on the console.

📌 Note: the print() function shows the following output:

[<User archie.andrews@email.com>, <User
...