在models中创建两个表
class Studentnew(db.Model): id = db.Column(db.Integer,primary_key=True) name = db.Column(db.String(20),unique=True) articles = db.relationship('Article', backref='stu', lazy='dynamic') #添加一对多的反向引用(引用的字段不会影响模型字段,不需迁移) #参数1:唯一的必传参数,关联的模型名 #backref:反向引用的字段名称 #lazy:关联查询数据的加载时机 # 'select'/True:首次使用时会自动查询,默认选项 # 'joined'/False:关联查询时进行查询 # 'subquery':在子查询时进行查询 # 'dynamic':不加载数据,在关联数据查询时查询(不能使用在一的一侧) class Article(db.Model): id = db.Column(db.Integer,primary_key=True) title = db.Column(db.String(40),unique=True) #添加外键关联,需要指定关联的'表名.字段' sid = db.Column(db.Integer,db.ForeignKey('studentnew.id'))
在views中创建相应的视图函数
#一对多关联查询 @blue.route('/onetomany/<id>/') def one_to_many(id): #根据学生查找文章 #原始查询 # articles = Article.query.filter(Article.sid == id).all() #模型关联查询 # stu = Studentnew.query.get(id) # articles = stu.articles.all() # return ','.join(a.title for a in articles) #根据文章找学生 article = Article.query.get(id) #原始查询 # student = Studentnew.query.get(article.sid) # return student.name #模型关联查询 return article.stu.name