首页 > 解决方案 > 如何更新现有数据并创建新的 django base 命令?

问题描述

我正在尝试从 json 文件中存储数据,并且我添加了添加数据不是问题,但是当我再次触发数据时,它们会复制数据并创建我不想要的相同的新数据,我希望它会更新现有数据如果 json 文件中有新数据,它将添加到 model 中。这是我的 django 基本命令代码。

from django.core.management.base import BaseCommand
import requests
from demo.models import CoronaAge, CoronaSex, CoronaComorbidity

class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        url = 'https://api.the2019ncov.com/api/fatality-rate'
        r = requests.get(url)
        titles = r.json()
        print(titles)

       # For between age
        for title in titles['byAge'] or []:
            CoronaAge.objects.update_or_create(
                age=title['age'],
                rate=title['rate']
            )

        context = {'titles': CoronaAge.objects.all()}

        # for sex wise male and female
        for title in titles['bySex'] or []:
            CoronaSex.objects.update_or_create(
                sex=title['sex'],
                rate=title['rate']
            )

        context = {'titles': CoronaSex.objects.all()}

        for title in titles['byComorbidity'] or []:
            CoronaComorbidity.objects.update_or_create(
                condition=title['preExistingCondition'],
                rate=title['rate']
            )

        context = {'titles': CoronaComorbidity.objects.all()}

标签: djangodjango-modelsdjango-rest-frameworkdjango-commands

解决方案


这就是我将如何解决它。获取列表现有数据。然后,对于每个新条目,检查它是否存在于数据库中,创建新对象,添加到列表中,最后运行 bulk_create 以一次性插入所有条目。如果存在,则更新您想要的所有字段,然后在最后运行批量更新。

corona_ages = CoronaAge.objects.all()
new_ages = []
existing_ages = []
for title in titles['byAge'] or []:
    entry = corona_ages.filter(age=title['age']).first():
    if not entry:
        new_data = CoronaAge(**title)
        new_ages.append(new_data)
    else:
        entry['some_param'] = title['some_param']
        entry['other_param'] = title['other_param']
        existing_ages.append(new_date)

CoronaAge.objects.bulk_create(new_ages)
CoronaAge.objects.bulk_update(existing_ages)

推荐阅读