One-to-Many Relationships
A one-to-many relationship means:
- one parent row relates to many child rows
Example:
- one
Userhas manyPosts
erDiagram
AUTHOR ||--o{ BOOK : writes
AUTHOR {
int id PK
string name
}
BOOK {
int id PK
string title
int author_id FK
}
Models
Section titled “Models”class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
posts = db.relationship("Post", back_populates="author", lazy=True)
class Post(db.Model):
__tablename__ = "posts"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(200), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
author = db.relationship("User", back_populates="posts")How to use it
Section titled “How to use it”user = User.query.first()
for post in user.posts:
print(post.title)lazy loading
Section titled “lazy loading”lazy=Truemeans posts are loaded when accessed
Be careful in loops (can cause N+1 queries).
You can optimize with eager loading later.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading