【问题标题】:How to update multiple records using peewee如何使用 peewee 更新多条记录
【发布时间】:2016-12-07 22:16:15
【问题描述】:

我将 Peewee 与 Postgres 数据库一起使用。我想知道如何一次更新表格中的多条记录?
我们可以使用these commands 在 SQL 中执行此更新,我正在寻找一种 Peewee 等效方法。

【问题讨论】:

  • 你试过Model.update()方法吗?
  • 是的,但我想知道性能。我最近开始学习,我红here多次插入单个项目是错误的,我找不到类似于insert_many的方法

标签: python postgresql peewee


【解决方案1】:

是的,你可以使用insert_many()函数:

一次插入多行。 rows 参数必须是可迭代的 产生字典。与 insert() 一样,字段不是 字典中指定的将使用它们的默认值,如果一个 存在。

例子:

usernames = ['charlie', 'huey', 'peewee', 'mickey']
row_dicts = ({'username': username} for username in usernames)

# Insert 4 new rows.
User.insert_many(row_dicts).execute()

更多详情请访问:http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.insert_many

【讨论】:

  • 但这是插入新项目,我想更新现有记录。
  • @alihaghighatkhah 然后使用单个.update(),如 Gordian 所述。它作为单个事务运行,而不是几个单独的更新操作。
  • 谢谢。是的,最终我将管道更改为使用update 方法
【解决方案2】:

ORM 通常不支持批量更新,您必须使用自定义 SQL,您可以在 link (db.excute_sql) 中查看示例

【讨论】:

    猜你喜欢
    • 2023-03-05
    • 2020-11-13
    • 1970-01-01
    • 2020-08-31
    • 2019-06-12
    • 1970-01-01
    • 2022-01-23
    • 2016-10-16
    • 1970-01-01
    相关资源
    最近更新 更多