如何在Peewee中批量插入获取id?

问题描述 投票:0回答:2

如何在Peewee中批量插入得到

ids

我需要返回插入的 id 来创建一个新的字典数组,如下所示:

a = [{"product_id": "inserted_id_1", "name": "name1"}, {"product_id": "inserted_id_2", "name": "name1"}]

然后我需要使用批量插入它,例如:

ids = query.insertBulk(a)

最后一个查询应该返回新的 id,以进行进一步的类似插入。

python python-3.x peewee flask-peewee
2个回答
4
投票

如果您使用 Postgresql,它支持“INSERT ... RETURNING”形式的查询,您可以获得所有 ID:

data = [{'product_id': 'foo', 'name': 'name1'}, {...}, ...]
id_list = SomeModel.insert_many(data).execute()

对于不支持 RETURNING 子句的 SQLite 或 MySQL,您最好这样做:

with db.atomic() as txn:
    accum = []
    for row in data:
        accum.append(SomeModel.insert(row).execute())

0
投票

如 peewee insert_many API 描述: https://docs.peewee-orm.com/en/latest/peewee/api.html#Model.insert_many

注意:默认返回值为修改的行数。然而,当使用 Postgres 时,Peewee 将默认返回一个游标,该游标生成插入行的主键。要使用 Postgres 禁用此功能,请使用对 returned() 的空调用。

因此,对于postgresql数据库,使用Model.insert_many函数返回一个迭代器,其中包含批量插入的记录ID。您需要遍历该迭代器来获取批量插入的记录ID。 例如:

data = [
    {'username': 'charlie', 'is_admin': True},
    {'username': 'huey', 'is_admin': False},
    {'username': 'zaizee', 'is_admin': False}
]
inserted_ids = []
# Insert new rows.
result = User.insert_many(data).execute()
for row in result:
    inserted_ids.append(row[0])
print(inserted_ids)
© www.soinside.com 2019 - 2024. All rights reserved.