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

后端 未结 2 492
我寻月下人不归
我寻月下人不归 2021-01-31 19:46

My application uses a combination of Flask, Flask-SQLAlchemy, Flask-WTF and Jinja2.

In its current incarnation, I have a settings table. The table will only have one rec

相关标签:
2条回答
  • 2021-01-31 20:18

    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.

    0 讨论(0)
  • 2021-01-31 20:34

    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)
    
    0 讨论(0)
提交回复
热议问题