Querying a database table with Flask SQLAlchemy is done through the query
property of the Model
class. To get all entries from a model called TableName
we run TableName.query.all()
. Often you know the primary key (unique identifier) value of entries you want to fetch. To get an entry with some primary key value ID
from model TableName
you run: TableName.query.get(ID)
.
For example, to get all the entries from the Reader
table we do the following:
readers = Reader.query.all()
Similarly, to get a reader with id = 123
we do the following:
reader = Reader.query.get(123)
We assign the result of the .get()
method to a variable because through that variable we can access the entry’s attributes. For example:
reader = Reader.query.get(450) print(reader.name)
Now you see the amazing convenience of using ORM: database tables are simply treated as Python classes and database entries are Python objects. For example, you can easily use a for
loop to loop through all the readers and print their name:
readers = Reader.query.all() for reader in readers: print(reader.name)
In the image on the right, you can see some entries we already inserted for you in the database, so you can query it.
Instructions
In the “playground.py” file, write code that to a variable called reviews
assigns all entries from the Review
table.
In the “playground.py” file, write a for
loop that will, for each review
in reviews
, print its text
attribute.
In the ‘playground.py’ file, write code that to a variable called book_1
assigns a book with id = 12
from the Book
table using the get()
function.