db.relationship sqlalchemy flask

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)
  1. Import the SQLAlchemy class from the flask_sqlalchemy module.
  2. Create an instance of the SQLAlchemy class named db.
  3. Define a User class that inherits from db.Model. This class represents the "User" table in the database.
  4. Add a primary key column id to the "User" table with the data type Integer.
  5. Add a column named username to the "User" table with the data type String(80), making it unique and not nullable.
  6. 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.
  7. Define a Post class that inherits from db.Model. This class represents the "Post" table in the database.
  8. Add a primary key column id to the "Post" table with the data type Integer.
  9. Add a column named title to the "Post" table with the data type String(120), making it not nullable.
  10. 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. ```