Flask-SQLAlchemy: How to conditionally insert or update a row

强颜欢笑 提交于 2019-12-02 17:37:30

Once your form is validated etc,

To add a new record:

new_provider = Provider(form.rssfeed.data)
db.session.add(new_provider)
db.session.commit()

To update an existing record:

existing_provider = Provider.query.get(1) # or whatever
# update the rssfeed column
existing_provider.rssfeed = form.rssfeed.data
db.session.commit()

The trick in updating is that you just have to change the particular field and do a commit. rest is taken care by the db session. I think you are using the merge function which is now deprecated in SQLAlchemy.

happygoat

I have managed to solve the problem doing these changes to the view.py file:

@app.route('/settings', methods=["GET","POST"])
def settings():
    """ show settings """
    provider = Provider.query.get(1)
    form = SettingsForm(request.form,obj=provider)

    if request.method == "POST" and form.validate():
        if provider:
            provider.rssfeed = form.rssfeed.data
            db.session.merge(provider)
            db.session.commit()
            flash("Settings changed")
            return redirect(url_for("index"))
        else:
            provider = Provider(form.rssfeed.data)
            db.session.add(provider)
            db.session.commit()
            flash("Settings added")
            return redirect(url_for("index"))
    return render_template("settings.html", form=form)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!