使用 Peewee 库批量更新

Bulk update using Peewee library

我正在尝试使用 Peewee 库更新 table 中的许多记录。在 for 循环中,我获取一条记录然后更新它,但这在性能方面听起来很糟糕,所以我需要批量更新。当前代码如下所示:

usernames_to_update = get_target_usernames()
for username in usernames_to_update:
    user = User.get(User.username == username) # username is primary key
    if user.type == 'type_1':
        user.some_attr_1 = some_value_1
    elif user.type == 'type_2':
        user.some_attr_2 = some_value_2
    # elif ....
    user.save()

documentation中,有insert_many函数,但没有update_many。四处寻找我想出了这些解决方案:

  1. 正在使用 CASE 执行原始查询:Link
  2. 使用replace_manyLink
  3. 使用update

但是我找不到任何关于如何使用第二种或第三种解决方案的示例。有人可以阐明如何使用案例 2 和案例 3 吗?

您需要 .update() 方法:

query = User.update(validated=True).where(User.username.in_(usernames_to_update))
query.execute()

Edit: 所以你想在更新期间有条件地设置值。您可以使用 Case 助手。未测试:

some_value_1 = 'foo'
some_value_2 = 'bar'
case_stmt = Case(User.type, [
    ('type_1', some_value_1),
    ('type_2', some_value_2)])
query = User.update(some_field=case_stmt).where(User.username.in_(list_of_usernames))
query.execute()

可在此处找到文档:http://docs.peewee-orm.com/en/latest/peewee/api.html#Case

新的最佳答案是使用找到的 bulk_update() 方法 here:

with database.atomic():
    User.bulk_update(user_list, fields=['username'], batch_size=50)