如何从Peewee批量插入中获取ID?

时间:2018-02-18 20:33:09

标签: python python-3.x peewee flask-peewee

如何在Peewee中批量插入ids

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

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

然后我需要使用批量插入这个:

ids = query.insertBulk(a)

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

1 个答案:

答案 0 :(得分:2)

如果你正在使用支持“INSERT ... RETURNING”形式查询的Postgresql,你可以获得所有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())