Start with something like this:
result = models.
What table do we want to query? Pizza?
result = models.Pizza.
And we're writing a query... so:
result = models.Pizza.query.
And do we want everything?
result = models.Pizza.query.all()
Or do we just want one thing:
result = models.Pizza.query.filter_by(something=something_else).first()
And what do we actually want? name="Hawaiian", id=3, etc. For example: SELECT * FROM Pizza WHERE name="Hawaiian";
result = models.Pizza.query.filter_by(name="Hawaiian").
And do we now want all pizzas called Hawaiian or just the first one?
result = models.Pizza.query.filter_by(name="Hawaiian").all()
or
result = models.Pizza.query.filter_by(name="Hawaiian").first()
Note: .first() queries will return an object with the results for a single entry, while .all() queries will return a list of those objects - even if there are no results (in which case an empty list will be returned). If no result is found for a .first() query then None will be returned. There is a special version of .first() to throw a 404 error for this case (which you often want to do:
result = models.Pizza.query.filter_by(name="Hawaiian").first_or_404()
Result is a terrible name for a variable, of course - a better name in this case would be pizza, or pizzas.
pizza = models.Pizza.query.filter_by(name="Hawaiian").first_or_404()
And you would access the members of the result something like this:
print(pizza.name) or {{ pizza.name }}
Great basic tutorial without the fluff. Get up and running really quickly with Flask-SQLAlchemy. Create Python Classes to define your data tables and generate a database from those- Remember, once they are made, you can still open up the database and add/delete data in SQLite Studio.
How do you create a one to many relationship in flask-sqlalchemy?
Anthony explains this really well in less than 6 minutes. It includes examples of creating the database, adding and querying. Everything you need to get started.
Sign up to this course.
Just bear in mind that Anthony uses the terminal to work with the database and we can use sqlite studio to create, edit and view the data. Pretty comprehensive courses though!!
Register here: https://prettyprinted.com/flasksql