I am trying to do a Model.objects.bulk_create(bulk_objects) in django, I am expecting IntegrityError's at times but I would like get the objects details that has caused the exception.
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
this throws the exception
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".
This is fine and I expect this, I am wanting to get the item_id that has caused the exception, in this case the item_id of 123865.
Is there a way of doing this without doing some regex on the string or iterating over the bulk_objects?
Was just hoping to get it directly from the error, otherwise I will continue with the regex approach
Exception raised when the relational integrity of the database is affected, eg a foreign key check fails, duplicate key, etc... So check if there are any duplicate entries, or any foreign key constraint of Database is failing.
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.
"""
According to docs bulk_create()
will not support Multi-table models. So you have to create a batch explicitly then send that batch to bulk_create()
. While creating that batch you can verify such things. You can check how to create a batch here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.