【问题标题】:Update multiple rows in ORM model at once一次更新 ORM 模型中的多行
【发布时间】:2022-01-20 10:33:02
【问题描述】:

我得到了这样的 orm 对象:

class Fruit(ModelBase):
    __tablename__ = "fruits"
    id = Column(BigInteger, nullable=False)
    name = Column(Unicode)
    price = Column(Integer)

我的桌子是这样的:

+----+--------+-------+
| id |  name  | price |
+----+--------+-------+
|  1 | apple  |   100 |
|  2 | carrot |   200 |
|  3 | orange |   300 |
+----+--------+-------+

我想用数据更新我的 orm 对象,所以我的表格如下所示:

+----+--------+-------+
| id |  name  | price |
+----+--------+-------+
|  1 | apple  |   500 |
|  2 | carrot |   200 |
|  3 | orange |   600 |
+----+--------+-------+

水果

updated_data = [{"id": 1, "name": "apple", "price": 500}, {"id": 3, "name": "orange", "price": 600}]

如何更新我的 orm 对象 Fruits 包含 updated_data 列表中的数据?

我试过了

update(Fruit).where(Fruit.id == updated_data.id).values(updated_data)

但它不起作用。

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    我认为如果你一次只做一行而不是将整个列表传递给 values(),你的代码会起作用。应该这样做:

    from sqlalchemy.orm import Session
    
    with Session(engine) as session:
        for fruit in updated_data:
            session.execute(
                update(Fruit).
                where(Fruit.id == fruit["id"]).
                values(fruit)
            )
        session.commit()
    

    如果对每一行运行一个查询结果很慢,您可以在此处查看此答案:SQLAlchemy update multiple rows in one transaction

    【讨论】:

      猜你喜欢
      • 2021-07-30
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 2016-06-04
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      • 2013-03-20
      相关资源
      最近更新 更多