gpt4 book ai didi

python - 如何在 peewee(python)的单个事务中保存所有实例?

转载 作者:太空宇宙 更新时间:2023-11-04 10:40:04 25 4
gpt4 key购买 nike

如何在 peewee 中的单个事务中保存所有实例(python orm库)?例如:

from peewee import SqliteDatabase, Model, TextField

DB_NAME = 'users.db'
db = SqliteDatabase(os.path.join(os.path.dirname(__file__), DB_NAME))


class Users(Model):

user_id = IntegerField(index = True)
name = TextField(null = True, index = True)
password = TextField(null = True)
description = TextField(null = True)
class Meta:
database = db

if not Drugs.table_exists():
Drugs.create_table()

data_to_save = [('user1', 'pass1'), ('user2', 'pass2'), ('user3', 'pass3')]

for user_name, user_password in data_to_save:
user_data = Users.get_or_create(name=user_name, password=user_password)
user_data.save()

如何在单个事务中重写?

最佳答案

您可以使用“with”上下文管理器包装您的查询https://docs.peewee-orm.com/en/3.4.0/peewee/transactions.html ,所以:

with db.transaction():
for user_name, user_password in data_to_save:
user_data = Users.get_or_create(name=user_name, password=user_password)
user_data.save()

关于python - 如何在 peewee(python)的单个事务中保存所有实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21188780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com