django批量插入,遇到错误改为逐条插入

为了提升插入数据的效率,通常采用批量插入的方式,当一批数据中有错误数据时,该批次数据报错,都插入失败。如何跳过引起报错的数据,将其他正确的数据插入,实现方式如下代码。

复制代码
data_to_insert = []
for i, data in  datas:
    testDemo = TestDemo()
    testDemo.ID = data[i].id
    testDemo.NAME = data[i].name
    data_to_insert.append(testDemo)

    if (i + 1) % 1000 == 0:
        try:
            TestDemo.objects.bulk_create(data_to_insert, batch_size=1000)
        except Exception as e:
            # 处理批次插入错误,逐个插入并跳过异常数据
            print("批次插入数据时出现错误:", e)
            for item in data_to_insert:
                try:
                    item.save()
                except Exception as e:
                    # 处理逐条插入错误,可以打印错误信息或进行其他操作
                    print("逐条插入数据时出现错误:", e)
        data_to_insert.clear()

# 处理最后可能剩余的数据
try:
    TestDemo.objects.bulk_create(data_to_insert, batch_size=1000)
except Exception as e:
    # 处理批次插入错误,逐个插入并跳过异常数据
    print("批次插入数据时出现错误:", e)
    for item in data_to_insert:
        try:
            item.save()
        except Exception as e:
            # 处理逐条插入错误,可以打印错误信息或进行其他操作
            print("逐条插入数据时出现错误:", e)
相关推荐
敏编程14 分钟前
一天一个Python库:tomlkit - 轻松解析和操作TOML配置
python
2401_8796938719 分钟前
使用Python进行图像识别:CNN卷积神经网络实战
jvm·数据库·python
yunyun3212326 分钟前
机器学习模型部署:将模型转化为Web API
jvm·数据库·python
团子和二花1 小时前
openclaw平替之nanobot源码解析(七):Gateway与多渠道集成
python·gateway·agent·智能体·openclaw·nanobot
未知鱼1 小时前
Python安全开发之简易目录扫描器(含详细注释)
开发语言·python·安全
Be1k01 小时前
推荐一款语雀知识库批量导出工具
python·gui·工具·语雀·批量导出·原创
Sunshine for you2 小时前
如何用FastAPI构建高性能的现代API
jvm·数据库·python
阿贵---2 小时前
Python Web爬虫入门:使用Requests和BeautifulSoup
jvm·数据库·python
Red丶哞2 小时前
内网自建Postfix使用Python发送邮件
开发语言·python
rebekk3 小时前
pytorch custom op的简单介绍
人工智能·pytorch·python