将生成的 JSON 保存到 SQLite - Django

我有这个代码:


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') 

结果jsonfromdata.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 有自己的方法来处理这些事情。


有任何想法吗?


绝地无双
浏览 235回答 1
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))         passreturn 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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python