12

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?

2 Answers2

22

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()
SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304
  • 7
    Off-topic: what does `ormically` mean? :) – RayLuo Sep 13 '18 at 20:04
  • 5
    @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. – bsplosion Jan 16 '19 at 16:26
  • @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. – SingleNegationElimination Jan 17 '19 at 18:51
6

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

This would work. Read about syncrhonize_session in sqlalchemy documentation.

YB Yu
  • 352
  • 1
  • 3
  • 9
  • 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. – Jeff C Jan 02 '20 at 20:47
  • strangely though if I use this code I usually get: `update() got an unexpected keyword argument 'name'` – AmazingMiki Nov 29 '20 at 03:17