简体   繁体   English

使用Flask SQLAlchemy更新特定行

[英]Updating a specific row with Flask SQLAlchemy

I have this app with a profile and I want to update only a specific row based on its account id. 我有一个带有配置文件的应用,我想根据其帐户ID仅更新特定行。 Inserting the data works, but updating a specific row doesn't and I'm not sure which part is wrong with my code. 插入数据是可行的,但是更新特定行却无效,而且我不确定代码的哪一部分有问题。

@app.route('/edit_parent/<int:acc_id>', methods=['GET','POST'])
def edit_parent(acc_id):
myParent = Parent.query.filter_by(acc_id=int(acc_id)).first()

if request.method == "POST":

    myParent.fname_p = request.form['fname_p']
    myParent.lname_p = request.form['lname_p']
    myParent.bday_p = request.form['bday_p']
    myParent.add_p = request.form['add_p']

    db.session.commit()
    print "hello success"
    return redirect(url_for('parent', acc_id=int(acc_id)))

if request.method == "GET":
    return render_template('edit_p.html', acc_id=int(acc_id))

It prints the "hello success" and redirects to the parent url but returns an error 302 and still no changes in the db. 它打印“ hello成功”并重定向到父URL,但返回错误302,并且数据库中仍然没有更改。

I don't think you are updating a specific row at all, but instead you are just inserting new one each time with: 我认为您根本不会更新特定的行,而只是每次都使用以下命令插入新的一行:

myParent = Parent(request.form['fname_p'], request.form['lname_p'], 
           request.form['bday_p'], request.form['add_p']).where(acc_id=acc_id)
db.session.add(myParent)`

So, what you are supposed to do instead is: 因此,您应该做的是:

myParent = Parent.query.filter_by(acc_id=acc_id)

assuming your Parent db has the following attributes: 假设您的Parent数据库具有以下属性:

myParent.fname = request.form['fname_p']
myParent.lname = request.form['lname_p']
myParent.bday  = request.form['bday_p']
myParent.add   = request.form['add_p']

db.session.commit()

solved it by adding: 通过添加以下内容解决了该问题:

myParent = db.session.merge(myParent)

this way it merges the current session with the previous one. 这样,它将当前会话与上一个会话合并。 It still returns a 302 but the data on the db has been successfully updated. 它仍然返回302,但是数据库上的数据已成功更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM