Updating a row using SQLAlchemy ORM

前端 未结 2 547
遇见更好的自我
遇见更好的自我 2021-01-18 06:22

Note: I am not using Flask-SQLAlchemy here, I\'m using SQLAlchemy ORM

I\'ve seen several answers on StackOverflow saying that this is a way to updat

2条回答
  •  盖世英雄少女心
    2021-01-18 06:56

    I believe you are looking for something like this for your update query:

    session.query(FoobarModel).filter(FoobarModel.id == foobar_id).update({'name': 'New Foobar Name!'})
    

    Since update() belongs to Query, and filter() does return a Query object, this will work, contrary to trying to call update() on your FoobarModel object (which does not have such a function) returned by Query.get(), see also here.

    As for looping over your properties and assigning them by name, you could do this with setattr and a dict, like this:

    foobar = session.query(FoobarModel).get(foobar_id)
    
    props = {'name': 'my new name'}
    
    for key, value in props.items():
        setattr(foobar, key, value)
    
    session.commit()
    session.flush()
    

    This is obviously a little pointless with just one property, but maybe it will come in handy at some point.

提交回复
热议问题