我正在尝试使用更新表内的许多记录Peewee图书馆。里面一个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()
In the 文档 http://docs.peewee-orm.com/en/latest/, 有insert_many
功能但没有什么类似的update_many
。搜索周围我想出了这些解决方案:
- 使用执行原始查询
CASE
: Link https://stackoverflow.com/a/11664726/10109777
- Using
replace_many
: Link http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.replace_many
- Using
update
: Link https://stackoverflow.com/a/41041164/10109777
但我找不到任何如何使用第二个或第三个解决方案的示例。有人可以澄清如何使用案例 2 和 3 吗?
新的最佳答案是使用bulk_update()
找到方法here http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.bulk_update:
with database.atomic():
User.bulk_update(user_list, fields=['username'], batch_size=50)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)