【问题标题】:Flask Sqlalchemy association table overwrites dataFlask Sqlalchemy 关联表覆盖数据
【发布时间】:2020-11-22 04:07:33
【问题描述】:

我创建了一个 api,用户将在其中向我发送 user_id 和 branch_id/branches_id,我的 api 将在我的关联表中插入记录。 例如 我的发帖请求是

{

    "branches" :  [2,3,4],
    "user_id" : 1

}

结果是

#   user_id branch_id
1   1   2
2   1   3
3   1   4

我的下一个帖子请求是

{

    "branches" :  [1],
    "user_id" : 1

}

这里我的关联表被覆盖了

#   user_id branch_id
1   1   1

这是我的代码 sn-p:

def post(self):       
    branch_ids = request.json['branches']
    user_id = request.json['user_id'] 
    if type(branch_ids)!= list :
        branch_ids = [branch_ids]
    branches = db.session.query(Branch).filter(Branch.id.in_(branch_ids)).all()
    if len(branch_ids) != len(branches):
        return "please select valid branches"
    user = db.session.query(User).filter(User.id == user_id).first()
    print(user)
    if user != None :
        user.branches = [branch for branch in branches]
        db.session.commit()
    else:
        return "user not found"
    return "done"

我想将分支分配给用户,并且我想从用户中删除分支。

【问题讨论】:

    标签: python python-3.x flask flask-sqlalchemy flask-marshmallow


    【解决方案1】:

    我没有追加到我的表中

    for branch in branches_id:
        user.branches.append(branch)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-16
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 2014-04-27
      • 2019-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多