V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
Jolly23
V2EX  ›  问与答

flask sqlalchemy 的一对多关系怎么添加数据?

  •  
  •   Jolly23 · 2016-08-04 11:04:34 +08:00 · 2998 次点击
    这是一个创建于 2793 天前的主题,其中的信息可能已经有所发展或是发生改变。

    flask sqlalchemy 的一对多关系怎么添加数据?

    举例:

    主-用户,唯一

    class UserInfo(db.Model):
    
    __tablename__ = 'user_info'
    
    id = db.Column(db.Integer, primary_key=True)
    
    u_id = db.Column(db.String(80), unique=True)
    
    u_account = db.relationship('Account', backref='user_info', lazy='dynamic')
    

    用户账户信息,多个系统,一个用户存多个账户

    class Account(db.Model):
    
    __tablename__ = 'account'
    
    id = db.Column(db.Integer, primary_key=True)
    
    a_info_id = db.Column(db.Integer, db.ForeignKey('user_info.id'))
    
    a_type = db.Column(db.Integer)	# 各系统编号
    
    a_account = db.Column(db.String(256))
    
    a_password = db.Column(db.String(256))
    

    然后代码里怎么添加用户的账户信息,假设用户已存在:

    current_user = UserInfo.query.filter_by(u_id=id).first()
    

    为 current_user 添加账户信息:

    new_account = Account(
    
            a_type=1,
    
            a_account=username,
    
            a_password=password,
    
        )
    

    请问怎么添加 new_account 能使得此账户信息属于 current_user ?

    我尝试过:

    new_account.user_info.append(current_user)
    
    db.session.add(new_account)
    
    db.session.commit()
    

    但是错了,这应该是多对多的添加方式,一对多该怎么写呢?

    1 条回复    2016-08-04 11:37:50 +08:00
    Jolly23
        1
    Jolly23  
    OP
       2016-08-04 11:37:50 +08:00
    问题已经解决了,由于 Account.a_info_id 的外键是 UserInfo.id ,所以直接给 new_account 加上
    new_account = Account(

    a_type=1,

    a_account=username,

    a_password=password,

    a_info_id=current_user.id

    )

    然后执行

    db.session.add(new_account)

    db.session.commit()

    就好了

    不太清楚这样解决问题是否最优,如果有更好的办法,也请大家提出交流,感谢 V2EX
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1378 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 23:39 · PVG 07:39 · LAX 16:39 · JFK 19:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.