我有此代码:
def getExchangeRates():
""" Here we have the function that will retrieve the latest rates from fixer.io """
rates = []
response = urlopen('http://data.fixer.io/api/latest?access_key=c2f5070ad78b0748111281f6475c0bdd')
data = response.read()
rdata = json.loads(data.decode(), parse_float=float)
rates_from_rdata = rdata.get('rates', {})
for rate_symbol in ['USD', 'GBP', 'HKD', 'AUD', 'JPY', 'SEK', 'NOK']:
try:
rates.append(rates_from_rdata[rate_symbol])
except KeyError:
logging.warning('rate for {} not found in rdata'.format(rate_symbol))
pass
return rates
@require_http_methods(['GET', 'POST'])
def index(request):
rates = getExchangeRates()
return render(request, 'index.html')
从json
得到的data.fixer.io
具有currency | rate_of_the_currency
之类的格式。
类似这样的事情:"rates": {"SAR": 4.394498, "INR": 49.836962, and so on...
,所以,我在Django上创建了此模型:
class Fixerio_rates(models.Model):
currency = models.CharField(max_length=128)
rate = models.FloatField()
现在,如何将代码中的结果保存到此模型中?已经进行了迁移,这不应该做复杂的事情,但是由于这是从Flask
到Django
的迁移,这让我有些困惑。这是一种不同的方法,Django有自己的方式来处理这些问题。
有什么想法吗?
答案 0 :(得分:1)
Django具有bulk_create queryset方法,该方法可在一个数据库查询中添加多个记录(有效方式)。因此您的代码应如下所示:
首先重写函数getExchangeRates,以便对所有货币获取一个字典,而不对每种货币获取字典
rates = {}
...
for rate_symbol in ['USD', 'GBP', 'HKD', 'AUD', 'JPY', 'SEK', 'NOK']:
try:
rates[rate_symbol] = rates_from_rdata[rate_symbol]
except KeyError:
logging.warning('rate for {} not found in rdata'.format(rate_symbol))
pass
return rates
然后遍历dict创建模型实例,然后将其大量保存。
rates = getExchangeRates()
fixerio_rates = [Fixerio_rates(currency=currency, rate=rate)
for currency, rate in rates.items()]
Fixerio_rates.objects.bulk_create(fixerio_rates)