Book Image

Mastering Flask

By : Jack Stouffer
Book Image

Mastering Flask

By: Jack Stouffer

Overview of this book

Starting from a simple Flask app, this book will walk through advanced topics while providing practical examples of the lessons learned. After building a simple Flask app, a proper app structure is demonstrated by transforming the app to use a Model-View-Controller (MVC) architecture. With a scalable structure in hand, the next chapters use Flask extensions to provide extra functionality to the app, including user login and registration, NoSQL querying, a REST API, an admin interface, and more. Next, you’ll discover how to use unit testing to take the guesswork away from making sure the code is performing as it should. The book closes with a discussion of the different platforms that are available to deploy a Flask app on, the pros and cons of each one, and how to deploy on each one.
Table of Contents (20 chapters)
Mastering Flask
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Relationships between models


Relationships between models in SQLAlchemy are links between two or more models that allow models to reference each other automatically. This allows naturally related data, such as comments to posts, to be easily retrieved from the database with its related data. This is where the R in RDBMS comes from, and it gives this type of database a large amount of power.

Let's create our first relation. Our blogging website is going to need some blog posts. Each blog post is going to be written by one user, so it makes sense to link posts back to the user that wrote them to easily get all posts by a user. This is an example of a one-to-many relationship.

One-to-many

Let's add a model to represent blog posts on our website:

class Post(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    title = db.Column(db.String(255))
    text = db.Column(db.Text())
    publish_date = db.Column(db.DateTime())
    user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))

...