Musius
Musius

Reputation: 95

Updating an entity with sqlalchemy ORM

I can't seem to find a way to update an entity in the database using sqlalchemy ORM

Here's what I'm doing:

 query = Table(self.table_name, self.sql_controller.metadata, autoload=True).select(ItemEntity)
 database_items: List[ItemEntity] = session.execute(query).all()
 database_items[0].Sell_price = 50000

But that raises an exception "AttributeError: can't set attribute"

I see that the same manipulation is being done in the official documentation of sqlalchemy https://docs.sqlalchemy.org/en/14/tutorial/orm_data_manipulation.html#updating-orm-objects

Can someone point me in the right direction? It's really irritating to fail at basic CRUD operations.

Upvotes: 1

Views: 663

Answers (1)

Gord Thompson
Gord Thompson

Reputation: 123829

Table objects are not part of SQLAlchemy ORM, they are part of SQLAlchemy Core. In order to use ORM you'll want to do something like this:

from sqlalchemy import create_engine
from sqlalchemy import select
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session

engine = create_engine("sqlite://", echo=True)

# create test environment
with engine.begin() as conn:
    conn.exec_driver_sql("CREATE TABLE my_thing (id int primary key, sell_price int)")
    conn.exec_driver_sql("INSERT INTO my_thing (id, sell_price) VALUES (1, 123)")

Base = automap_base()


class MyThing(Base):
    __tablename__ = "my_thing"


Base.prepare(autoload_with=engine)

# test
with Session(engine) as sess:
    thing_1 = sess.scalar(select(MyThing).where(MyThing.id == 1))
    thing_1.sell_price = 456
    sess.commit()
""" SQL emitted:
UPDATE my_thing SET sell_price=? WHERE my_thing.id = ?
[generated in 0.00032s] (456, 1)
"""

Upvotes: 1

Related Questions