Peeweebulk_create 返回 id 的

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

如果peewee中的记录来自bulk_create,我需要返回id

我可以做这样的事情

from models import Table

t = Table.create(**data)
print(i.id)

我得到了新记录的ID

但是如果我尝试

t = Table.bulk_create(list[**data])
for i in t:
    print(i.id)

这里我收到错误:“t”是“NoneType”

那么我怎样才能从peeweebulk_create中获取id呢?

python database orm peewee
2个回答
3
投票

Peewee does 返回 ID 列表 if 您使用的数据库支持

RETURNING
子句。因此,如果您使用 Postgresql,那么 peewee 将返回 ID 列表。

使用

bulk_create()
的原因是因为它发出有效的查询——一次插入多行。 Sqlite 和 mysql 只提供“最后插入 id”。


0
投票

在最新的peewee版本(3.17.1,其他较新的版本可能也一样),可以尝试以下方法:

插入多个

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

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.