search

Home  >  Q&A  >  body text

python - How does SQLAlchemy insert data into the corresponding id?

I want to insert or modify a piece of data in the row corresponding to the id, but I don’t know how to do it

巴扎黑巴扎黑2791 days ago769

reply all(2)I'll reply

  • 習慣沉默

    習慣沉默2017-05-24 11:36:51

    To add, delete, check and modify, just go to the document.

    model = Model.query.get(id)
    or model = Model.query.filter_by(id=id).first()
    
    model.name = 'new name'
    
    db.session.add(model)
    db.session.commit()
    

    reply
    0
  • 黄舟

    黄舟2017-05-24 11:36:51

    If you insert data by specifying the ID, it is unlikely if it is the primary key, but it can be updated. And if it is not the primary key, then 2 operations can be achieved. The code is similar to the following:

    Add as:

    model = Model(name='new names')
    db.session.add(model)
    db.session.commit()

    Then update to:

    model.name = 'new name'
    db.session.add(model)
    db.session.commit()

    reply
    0
  • Cancelreply