您的位置:首页 >Django 批量导入 JSON 数据的高效方法
发布于2026-04-16 阅读(0)
扫一扫,手机访问

本文详解如何在 Django 中安全、高效地将 JSON 文件数据批量写入 SQL 数据库,重点纠正单条保存导致的数据丢失问题,并推荐使用 bulk_create() 实现一次性高性能插入。
本文详解如何在 Django 中安全、高效地将 JSON 文件数据批量写入 SQL 数据库,重点纠正单条保存导致的数据丢失问题,并推荐使用 `bulk_create()` 实现一次性高性能插入。
在 Django Web 开发中,常需将外部 JSON 数据(如分析报告、API 响应或本地配置文件)持久化到数据库。但初学者易犯一个典型错误:在循环中逐条创建模型实例,却仅在循环外调用 .save() —— 这会导致仅有最后一个 JSON 条目被写入数据库,其余全部丢失。
以下为修正后的标准做法,核心是使用 Django 提供的 .bulk_create() 方法:
from django.shortcuts import render
import json
from .models import MyModel
import os
def display(request):
# 安全构建 JSON 文件路径(推荐使用 pathlib 替代 os.path 拼接)
json_file_path = os.path.join(
os.path.dirname(__file__), '..', '..', 'jsondata.json'
)
try:
with open(json_file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
# ✅ 正确:列表推导式批量构建模型实例(不触发数据库操作)
my_models = [
MyModel(
end_year=item.get('end_year'),
intensity=item.get('intensity'),
sector=item.get('sector'),
topic=item.get('topic'),
insight=item.get('insight'),
url=item.get('url'),
region=item.get('region'),
start_year=item.get('start_year'),
impact=item.get('impact'),
added=item.get('added'),
published=item.get('published'),
country=item.get('country'),
relevance=item.get('relevance'),
pestle=item.get('pestle'),
source=item.get('source'),
title=item.get('title'),
likelihood=item.get('likelihood'),
)
for item in data
]
# ✅ 一次性批量写入数据库(性能提升显著,尤其对千级以上数据)
MyModel.objects.bulk_create(my_models, batch_size=1000)
except FileNotFoundError:
data = []
print(f"Warning: JSON file not found at {json_file_path}")
except json.JSONDecodeError as e:
print(f"Invalid JSON format: {e}")
data = []
except Exception as e:
print(f"Unexpected error during bulk import: {e}")
data = []
return render(request, 'display.html', {'data': data})✅ 关键改进说明:
掌握此模式,即可在 Django 项目中可靠、高效地完成结构化数据迁移任务。
下一篇:233漫画正版入口免费在线看
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9