首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在django bulk_create中获取bulk_create的密钥

在django bulk_create中获取bulk_create的密钥
EN

Stack Overflow用户
提问于 2018-06-15 04:09:18
回答 1查看 1.4K关注 0票数 3

我正试图在django中做一个Model.objects.bulk_create(bulk_objects),我有时会期待IntegrityError,但是我想获得导致异常的对象细节。

代码语言:javascript
复制
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

这会引发异常。

代码语言:javascript
复制
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方法。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-15 05:50:47

当数据库的关系完整性受到影响时引发异常,例如外键检查失败、重复密钥等。因此,请检查是否有重复的条目,或者任何数据库的外键约束都失败了。

代码语言:javascript
复制
    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()。在创建该批时,您可以验证这些内容。您可以检查如何创建批处理这里

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50868980

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档