简体   繁体   中英

How to get (Retrieve) data from SQlite database in Flask using sqlalchemy

I have a form in my flask application that collects emails, usernames, and phone numbers. I have stored them all in the SQLite database using flask sqlalchemy. Let's say my database looks like the following:

Email                    Username                     Phone Number
James@yahoo.com           James                          123456789
 Jane@yahoo.com            Jane                          987654321

I have an HTML file and I would like to display data there. What I have is:

> @app.route("/Display") 
  def Display():
     # Here I want to get all data from the database
     # like this data=get from database 
     return render_template('Display.html', data=data)

I would like to know can anyone tell me how to retrieve data or get the data from database using flask sqlalchemy ORM. I know query.filter_by can be used to filter according to a username or email or phone number. However, how can I get the whole table (like in a form to pass to render_template? like in HTML page I want to loop through data and use data.username or data.email)

You can use this code to retrieve everything

data = Model.query.all()

Where model is the name of your model. This returns a list of the objects.

If you want to filter the data by a specific value:

data = Model.query.filter_by(attribute=value)

You can add .all() if you want to get all instances of your Model matching the value.

If you want to filter by the ID of the data:

data = Model.get_or_404(dataID)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM