数据传输到SQL

问题描述 投票:0回答:1
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。

python sql json django django-views
1个回答
1
投票

您将项目保存在for循环之外

,因此它只会保存最后一行,因为在循环结束时
my_model_instance
将指向创建的最后一个项目。

我们可以创建一个项目列表,并使用

.bulk_create(…)

 [Django-doc] 将所有项目添加到 one 查询中的数据库中:

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})
    
© www.soinside.com 2019 - 2024. All rights reserved.