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

后端 未结 2 493
我寻月下人不归
我寻月下人不归 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.

提交回复
热议问题