在 django 中获取 IntegrityError 的密钥 bulk_create

Get key of IntegrityError in django bulk_create

我正在尝试在 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() 将不支持 Multi-table 模型。因此,您必须显式创建一个批次,然后将该批次发送到 bulk_create()。在创建该批次时,您可以验证这些事情。 您可以查看如何创建批处理 here.