Retrieval
Explore various methods for retrieving records from databases in Flask using SQLAlchemy ORM. Understand how to use query.all, first, get, filter_by, and filter functions to fetch data effectively. This lesson helps you gain practical skills to query your models, inspect results, and refine database queries for your Flask web apps.
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.
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 theUsermodel 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 veronica.lodge@email.com>]This ...