Updating specific row in SQLAlchemy

16,593

Solution 1

ormically, you don't use update(), you set attributes:

a_user = session.query(User).filter(User.id == 3).one()
a_user.name = "user"
session.commit()

Solution 2

session.query(User).filter(User.id==3).update({'name':'user'},synchronize_session=False)

This would work. Read about syncrhonize_session in sqlalchemy documentation.

Share:
16,593
Mohamed Abd El Raouf
Author by

Mohamed Abd El Raouf

Software engineer graduated from Faculty of computers and information cairo university...

Updated on June 04, 2022

Comments

  • Mohamed Abd El Raouf
    Mohamed Abd El Raouf almost 2 years

    I'm using SQLAlchemy with python and i want to update specific row in a table which equal this query:

    UPDATE User SET name = 'user' WHERE id = '3'
    

    I made this code by sql alchemy but it's not working:

    session.query(User).filter(User.id==3).update({'name': 'user'})
    

    returned this error:

    InvalidRequestError: Could not evaluate current criteria in Python. Specify 'fetch' or False for the synchronize_session parameter.
    

    How can i do it?

  • RayLuo
    RayLuo over 5 years
    Off-topic: what does ormically mean? :)
  • bsplosion
    bsplosion over 5 years
    @RayLuo, I suspect by ormically they meant "when leveraging the ORM coding approach" - essentially, leveraging database objects as Python objects via SQL Alchemy rather than constructing queries to manipulate data.
  • SingleNegationElimination
    SingleNegationElimination over 5 years
    @bsplosion @RayLuo there are to main "areas" of the SqlAlchemy library, the "expression" layer, which operates on a very sql oriented, relational style; and the "orm" layer, which is built on top of the expression layer, that "maps" sql tables to python classes. "ormically" would be using the latter half of sqlalchemy to do things, but update() belongs to the former.
  • user1556937
    user1556937 over 4 years
    Your comment just saved me. I used synchronize_session='fetch' and it first queries the data before running the update on the db. would have preferred it ran the update at once and let the db decide on whether to apply the update command or not.
  • AmazingMiki
    AmazingMiki over 3 years
    strangely though if I use this code I usually get: update() got an unexpected keyword argument 'name'