from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
posts = db.relationship('Post', backref='user', lazy=True)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(120), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
- Import the
SQLAlchemy
class from the flask_sqlalchemy
module. - Create an instance of the
SQLAlchemy
class named db
. - Define a
User
class that inherits from db.Model
. This class represents the "User" table in the database. - Add a primary key column
id
to the "User" table with the data type Integer
. - Add a column named
username
to the "User" table with the data type String(80)
, making it unique and not nullable. - Establish a one-to-many relationship between the "User" and "Post" tables using the
db.relationship
function. The backref
parameter creates a reverse reference from the "Post" table to the "User" table, and the lazy
parameter specifies that the relationship should be loaded lazily. - Define a
Post
class that inherits from db.Model
. This class represents the "Post" table in the database. - Add a primary key column
id
to the "Post" table with the data type Integer
. - Add a column named
title
to the "Post" table with the data type String(120)
, making it not nullable. - Add a foreign key column
user_id
to the "Post" table with the data type Integer
. This column references the id
column of the "User" table using db.ForeignKey('user.id')
, establishing the foreign key relationship.
```