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

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

如何从 Peewee 中的批量插入中获取 ids

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

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

然后我需要像这样批量插入:

ids = query.insertBulk(a)

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

最佳答案

如果您使用的是 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())

关于python - 如何从批量插入 Peewee 中获取 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48856291/

相关文章:

python - 使用 VBA 运行 .exe

python - 应用引擎 : Will the items stored in a StringListProperty always remain in the same order?

python - 将字符添加到特定的重复字符串

python - 即使用户和密码正确,Postgresql/psycopg2 密码验证错误

python - 在 Peewee 中允许空值

python - Django-admin.py 在我的共享主机环境中产生错误

arrays - 不同大小数组(锯齿数组)的Python集合,Dask?

Python 从包中安装子包

Python:Peewee 更新查询不起作用

python - 如何修复指出字符串无法转换为 float 的值错误