我正试图在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的方法?
我只是希望从错误中直接得到它,否则我将继续使用regex方法。
发布于 2018-06-15 05:50:47
当数据库的关系完整性受到影响时引发异常,例如外键检查失败、重复密钥等。因此,请检查是否有重复的条目,或者任何数据库的外键约束都失败了。
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.
"""根据docs的说法,bulk_create()不支持多表模型。因此,您必须显式地创建一个批处理,然后将该批处理发送到bulk_create()。在创建该批时,您可以验证这些内容。您可以检查如何创建批处理这里。
https://stackoverflow.com/questions/50868980
复制相似问题