1、一对多关系
双向关系的例子:使用back_populates来定义,两边都需要加添加
class Writer(db.Model): books=db.relationship('Book',back_populates='writer') class Book(db.Model): writer_id=db.Column(db.Integer,db.ForeignKey('writer.id')) writer=db.relationship('Writer',back_populations='books')
双向关系:使用backref,简化
class Writer(db.Model): books=db.relationship('Book',backref='writer') class Book(db.Model): writer_id=db.Column(db.Integer,db.ForeignKey('writer.id'))
2、多对一关系:
image.png
3、一对一关系 class Country(db.Model): capital=db.relationship('Capital',uselist=False) class Capital(db.Model): country_id=db.Column(db.Integer,db.ForeignKey('country.id')) country=db.relationship('Country')
4、多对多关系 association_table=db.Table('association',db.Column('student_id',db.Integer,db.ForeignKey('student.id')),db.Column('teacher_id',db.Integer,db.ForeignKey('teacher.id'))) class Student(db.Model): teachers=db.relationship('Teacher',secondary=association_table,back_populates='students') class Teacher(db.Model): students=db.relationship('Student',secondary=association_table,back_populates='teachers')
关系的添加和移除:append() remove() db.drop_all() db.create_all()
多对一关系映射
authod_id=db.Column(db.Integer,db.Foreignkey('author.id'))
一对多
articles=db.relationship('Article')
解除: foo.articles.remove(spam)
db关系:
image.png
db关系的加载方式: select 必要时一次性加载全部 joined 级联加载 immediate 全部加载 subquery 子查询加载 dynamic 不直接加载