SQLAlchemy在for循环中添加/更新:更新不起作用

时间:2019-05-02 15:55:44

标签: flask sqlalchemy

我正在尝试执行以下操作:遍历一系列记录,如果已经存在,则对其进行更新。如果不存在,请添加它。

由于某种原因,添加工作正常,但未进行更新。这是代码:

for interchange in data:
    ltype='asdf'
    plink='qwer'

    e = Part.query.filter_by(interchange=interchange, light_type=ltype).first()
    if e is None:
        notpresent = notpresent + 1
        p = Part(interchange=interchange,light_type=ltype,partslink=plink,ptype=ptype)
        db.session.add(p)
    else:
        present = present + 1
        e.partslink = plink
        e.ptype = ptype

db.session.commit()

我打印出存在和不存在的变量,并且都>0。

找到记录后,我是否错误地处理了更新部件?那部分没有得到保存。

1 个答案:

答案 0 :(得分:0)

您缺少一行:

# ...
else:
    present = present + 1
    e.partslink = plink
    e.ptype = ptype    
    db.session.add(e)  # here 'add' is adding changes to the session, not a new item.

如果不注册,则无法提交更改。

相关问题