【问题标题】:Get key of IntegrityError in django bulk_create在 django bulk_create 中获取 IntegrityError 的键
【发布时间】:2018-06-15 04:09:18
【问题描述】:

我正在尝试在 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 的情况下做到这一点?

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

【问题讨论】:

  • 没有办法直接获取key

标签: python django bulkinsert


【解决方案1】:

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

    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

【讨论】:

  • 我知道为什么会引发异常,这不是我遇到的问题。我所追求的是导致异常的特定对象,它可能是 70k+ 对象中的 1 个。我希望我可以从引发的错误中提取它,但无法弄清楚那部分。目前我正在使用正则表达式从字符串e.__cause__ 中获取对象详细信息
  • Key (item_id)=(123865) is not present in table "item_table". 所以item_id=123865item_table 中不存在,所以它会给你错误,你可以整理出 item_id 为 123865 的对象,因为它们会导致错误。
  • 是的,我知道我的item_table 缺少 id 为 123865 的项目,我可以手动修复它。我在问是否有办法以编程方式获取导致错误的项目 id,这样我可以在程序中相应地处理它,而不是手动读取错误日志并进行手动更改。我正在使用正则表达式获取 id,我只是想知道是否还有其他方法。
猜你喜欢
  • 1970-01-01
  • 2012-09-09
  • 2012-06-03
  • 2013-04-02
  • 1970-01-01
  • 2014-07-22
  • 2016-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多