[英]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()
将不支持多表模型。 因此,您必须显式创建一个批次,然后将该批次发送到bulk_create()
。 创建该批处理时,您可以验证这些内容。 您可以在此处检查如何创建批处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.