ORM Relationships (Flask-SQLAlchemy)

Relationships in Flask-SQLAlchemy connect models together — one-to-many, one-to-one, and many-to-many — so you can navigate from one object to its related objects in Python, like user.posts, without writing JOIN SQL.

Flask

Relational data is linked by foreign keys. A db.ForeignKey('user.id') column on Post stores which user owns it, and a db.relationship('Post', backref='author') on User lets you read user.posts and post.author as ordinary Python attributes.

One-to-many is the most common: the 'many' side holds the foreign key, the 'one' side declares the relationship. Many-to-many requires an association table (a secondary= argument) because neither side can hold a single foreign key.

Relationships load lazily by default, meaning the related rows are fetched only when you access them. This can cause the N+1 query problem in loops; use joinedload or selectinload to fetch related rows up front when iterating.

Syntax

posts = db.relationship("Post", backref="author")

Examples

Python

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    posts = db.relationship("Post", backref="author")

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"))

# user.posts -> list of Post; post.author -> User

Learn it in a lesson

See also

Back to the Dictionary