一、一对多模型
在多的一方定义外键关联一的一方
# 一的一方
class Role(db.Model):
"""角色表"""
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
users = db.relationship('User', backref='role', lazy='dynamic')
# 多的一方
class User(db.Model):
"""用户表"""
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True, index=True)
# 多的一方定义外键关联多的一方
role_id = db.Column(db.Integer, db.ForeignKey(Role.id))
二、多对多
建立中间表:关联数据库
代码实例:
# 中间表
tb_student_course = db.Table('tb_student_course',
db.Column('student_id', db.Integer, db.ForeignKey('students.id')),
db.Column('sport_id', db.Integer, db.ForeignKey('sports.id'))
)
# 学生表
class Student(db.Model):
__tablename__ = "students"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
# 方便查询 懒加载,使用时才真正查询
sports = db.relationship('Sport', secondary=tb_student_course,
backref=db.backref('students', lazy='dynamic'),
lazy='dynamic')
class Sport(db.Model):
__tablename__ = "sports"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
三、自关联一对多
外键关联自己:
class Comment(db.Model):
"""评论"""
__tablename__ = "comments"
id = db.Column(db.Integer, primary_key=True)
# 评论内容
content = db.Column(db.Text, nullable=False)
# 父评论id 自关联自己
parent_id = db.Column(db.Integer, db.ForeignKey("comments.id"))
# 父评论(也是评论模型)
parent = db.relationship("Comment", remote_side=[id],
backref=db.backref('childs', lazy='dynamic'))
四、自关联多对多
建立中间表:
tb_user_follows = db.Table(
"tb_user_follows", # 中间表名
db.Column('follower_id', db.Integer, db.ForeignKey('info_user.id'), primary_key=True), # 粉丝id
db.Column('followed_id', db.Integer, db.ForeignKey('info_user.id'), primary_key=True) # 被关注人的id
)
class User(db.Model):
"""用户表"""
__tablename__ = "info_user"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(32), unique=True, nullable=False)
# 用户所有的粉丝,添加了反向引用followed,代表用户都关注了哪些人
followers = db.relationship('User',
secondary=tb_user_follows,
primaryjoin=id == tb_user_follows.c.followed_id,
secondaryjoin=id == tb_user_follows.c.follower_id,
backref=db.backref('followed', lazy='dynamic'),
lazy='dynamic')