gpt4 book ai didi

python - 在 django bulk_create 中获取 IntegrityError 的 key

转载 作者:行者123 更新时间:2023-12-05 08:08:14 24 4
gpt4 key购买 nike

我正在尝试在 django 中执行 Model.objects.bulk_create(bulk_objects),我有时会期待 IntegrityError,但我想获取导致异常的对象详细信息。

try:
# bulk_objects contains ~70k items
Auction.objects.bulk_create(bulk_objects)
except IntegrityError as e:
print(str(e.__cause__))
msg = str(e.__cause__)
match = re.search('(?!\()\d+(?=\))', msg)
print(match.group(0)) # prints 123865 in this case

这会抛出异常

insert or update on table "auction_table" violates foreign key constraint"my_constraint"
DETAIL: Key (item_id)=(123865) is not present in table "item_table".

这很好,我希望如此,我想获取导致异常的 item_id,在本例中为 123865 的 item_id。

有没有一种方法可以在不对字符串执行正则表达式或遍历 bulk_objects 的情况下执行此操作?

只是希望直接从错误中得到它,否则我将继续使用正则表达式方法

最佳答案

当数据库的关系完整性受到影响时引发异常,例如外键检查失败、重复键等...所以检查是否有任何重复条目,或者数据库的任何外键约束失败。

    def bulk_create(self, objs, batch_size=None):
"""
Inserts each of the instances into the database. This does *not* call
save() on each of the instances, does not send any pre/post save
signals, and does not set the primary key attribute if it is an
autoincrement field (except if features.can_return_ids_from_bulk_insert=True).
Multi-table models are not supported.
"""

根据文档 bulk_create() 将不支持多表模型。因此,您必须显式创建一个批处理,然后将该批处理发送到 bulk_create()。在创建该批处理时,您可以验证这些事情。您可以查看如何创建批处理 here .

关于python - 在 django bulk_create 中获取 IntegrityError 的 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50868980/

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