flask 一对多关系 主从表之间查询

在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

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值