django - 如何更新现有数据并创建新的 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()}
解决方案
这就是我将如何解决它。获取列表现有数据。然后,对于每个新条目,检查它是否存在于数据库中,创建新对象,添加到列表中,最后运行 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)
推荐阅读
- php - 更新特定行 textarea 和 mysql
- html - 下拉菜单中的二级下拉菜单未显示
- java - 只读访问基于 tomcat Web 应用程序的用户角色
- ruby-on-rails-3 - Rails:如何显示数据库中是否已存在值
- php - 非贪婪提取非常长的文本时的正则表达式 PREG_BACKTRACK_LIMIT_ERROR
- r - Rmarkdown 文档的字体
- java - Java Android 从 Firebase 检索推送的密钥数据
- php - laravel created_at 保存时的时区不正确
- eclipse - 如何在 Eclipse IDE 中将默认比较模式从二进制更改为文本
- angularjs - angularjs-高亮文本成段落