数据传输到SQL

0 投票
1 回答
39 浏览
提问于 2025-04-14 15:51
from django.shortcuts import render
import json
from .models import MyModel
import os


def display(request):
    json_file_path = os.path.join(os.path.dirname(__file__), '..', '..', './jsondata.json')
    try:
        with open(json_file_path, 'r') as f:
            data = json.load(f)
            for item in data:
                my_model_instance = MyModel(end_year=item['end_year'], intensity=item['intensity'],
                                            sector=item['sector'], topic=item['topic'], insight=item['insight'],
                                            url=item['url'], region=item['region'], start_year=item['start_year'],
                                            impact=item['impact'], added=item['added'], published=item['published'],
                                            country=item['country'], relevance=item['relevance'], pestle=item['pestle'],
                                            source=item['source'], title=item['title'], likelihood=item['likelihood'])
            my_model_instance.save()
    except FileNotFoundError:
        data = []

    template_name = 'display'
    return render(request, template_name, {'data': data})

我正在尝试使用Django把JSON中的数据转移到SQL数据库里。

1 个回答

3

你把这个项目保存在循环外面,所以它只会保存最后一行,因为在循环结束时,my_model_instance会指向最后创建的那个项目。

我们可以先把所有项目放到一个列表里,然后使用.bulk_create(…) [Django-doc]一次性把所有项目添加到数据库中,这样只需要一次查询:

from django.shortcuts import render
import json
from .models import MyModel
import os

def display(request):
    json_file_path = os.path.join(
        os.path.dirname(__file__), '..', '..', './jsondata.json'
    )
    with open(json_file_path, 'r') as f:
        data = json.load(f)
        my_models = [
            MyModel(
                end_year=item['end_year'],
                intensity=item['intensity'],
                sector=item['sector'],
                topic=item['topic'],
                insight=item['insight'],
                url=item['url'],
                region=item['region'],
                start_year=item['start_year'],
                impact=item['impact'],
                added=item['added'],
                published=item['published'],
                country=item['country'],
                relevance=item['relevance'],
                pestle=item['pestle'],
                source=item['source'],
                title=item['title'],
                likelihood=item['likelihood'],
            )
            for item in data
        ]
        MyModel.objects.bulk_create(my_models)

    template_name = 'display'
    return render(request, template_name, {'data': data})

撰写回答