一對多
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)
多對多
tb_student_course = db.Table('tb_student_course',
db.Column('student_id', db.Integer, db.ForeignKey('students.id')),
db.Column('course_id', db.Integer, db.ForeignKey('courses.id'))
)
class Student(db.Model):
__tablename__ = "students"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
courses = db.relationship('Course', secondary=tb_student_course,
backref=db.backref('students', lazy='dynamic'),
lazy='dynamic')
class Course(db.Model):
__tablename__ = "courses"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
自關(guān)聯(lián)一對多
class Comment(db.Model):
"""評論"""
__tablename__ = "comments"
id = db.Column(db.Integer, primary_key=True)
# 評論內(nèi)容
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'))
# 測試代碼
if __name__ == '__main__':
db.drop_all()
db.create_all()
com1 = Comment(content='我是主評論1')
com2 = Comment(content='我是主評論2')
com11 = Comment(content='我是回復(fù)主評論1的子評論1')
com11.parent = com1
com12 = Comment(content='我是回復(fù)主評論1的子評論2')
com12.parent = com1
db.session.add_all([com1, com2, com11, com12])
db.session.commit()
app.run(debug=True)
自關(guān)聯(lián)多對多
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) # 被關(guān)注人的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,代表用戶都關(guān)注了哪些人
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')