使用sqlalchemy ORM更新实体



我似乎找不到使用sqlalchemy ORM 更新数据库中实体的方法

我在做什么:

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

但这引发了一个例外";AttributeError:无法设置属性">

我在sqlalchemy的官方文档中看到了同样的操作https://docs.sqlalchemy.org/en/14/tutorial/orm_data_manipulation.html#updating-orm对象

有人能给我指正确的方向吗?基本CRUD操作失败真的很令人恼火。

Table对象不是SQLAlchemy ORM的一部分,它们是SQLAlchemyCore的一部分。为了使用ORM,你需要做这样的事情:

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)
"""

最新更新