In order to read data from the database, you will need to define it in your route for your page and then call it in the page using the Jinja2 templating language.
Ensure that you are importing the model at the top of your routes.py file and then do two things to your route:
-
Either:
- Assign a variable to a list of all of the instances of a Model
- Assign a variable to a specific instance of a Model. When doing this,
.first()is required as you are only looking for one record.
- Add that variable to the return list
# The following is defined within a route
# Get all categories as a list ordered alphabetically by the a class attribute category_name
categories = list(Category.query.order_by(Category.category_name).all())
# Get the category with an category_name of "Category Name"
category_name = Category.query.filter_by(category_name="Category Name").first()
# Get the cateogry with the id of 1
category_id = Category.query.filter_by(id=1).first()
# Add these to the return
return render_template(
"categories.html",
categories = categories,
category_name = category_name,
category_id = category_id
)
The returns look a little silly with
categories = categories
etc. This is done to keep the code consistent but in reality the left hand side of that equals is the variable
name that is sent to your webpage in the templating language and the right hand side is the name of the variable
defined above within the route.