簡體   English   中英

在Django bulk_create中獲取IntegrityError的鍵

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM