This example creates an author and two posts linked to that author. It then prints the author's name and the titles of their posts.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class Author(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
posts = db.relationship('Post', back_populates='author')
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100))
author_id = db.Column(db.Integer, db.ForeignKey('author.id'))
author = db.relationship('Author', back_populates='posts')
with app.app_context():
db.create_all()
# Create an author
author = Author(name='Alice')
db.session.add(author)
db.session.commit()
# Create posts linked to author
post1 = Post(title='First Post', author=author)
post2 = Post(title='Second Post', author=author)
db.session.add_all([post1, post2])
db.session.commit()
# Print author and their posts
print(f"Author: {author.name}")
for post in author.posts:
print(f"- Post: {post.title}")