django 在for循环中解包需要2个值;得到4

qoefvg9y  于 2023-05-01  发布在  Go
关注(0)|答案(2)|浏览(89)

我是Django的新手,正在尝试使用上下文将API结果(列表中的字典)传递给模板。
我试过这么做

{% if apiList != "Error..." %}
    {% for i in apiList %}
      {% for key, value in i %}
        {{ key }} {{ value }}<br>
      {% endfor %}
    {% endfor %}
  {% endif %}

但我得到了错误

Need 2 values to unpack in for loop; got 4.

当我执行同样的代码,但取出值,所以它只是搜索键,它工作正常,并在新的一行打印出所有的键。我还尝试了下面的代码:

{% for key, value in apiList.items %}
   {{ key }} : {{ value }}
{% endfor %}

但这似乎也不起作用,它没有给予出错误,但屏幕上什么都没有显示。
你知道怎么解决这个问题吗?下面是我在www. example中的代码 www.example.com

try:
            apiList = json.loads(api_request.content)

        except Exception as e:
            apiList = "Error..."
        return render(request, 'financials.html', {'apiList': apiList})
    else:
        return render(request, 'financials.html', {})

谢谢!
编辑:以下是apiList中的数据示例:

[
{
date: "2020-09-26",
symbol: "AAPL",
fillingDate: "2020-10-30",
acceptedDate: "2020-10-29 18:06:25",
period: "FY",
revenue: 274515000000,
costOfRevenue: 169559000000,
grossProfit: 104956000000,
grossProfitRatio: 0.382332477278109,
researchAndDevelopmentExpenses: 18752000000,
generalAndAdministrativeExpenses: 19916000000,
sellingAndMarketingExpenses: 0,
otherExpenses: 803000000,
operatingExpenses: 38668000000,
costAndExpenses: 208227000000,
interestExpense: 0,
depreciationAndAmortization: 11056000000,
ebitda: 77344000000,
ebitdaratio: 0.281747809773601,
operatingIncome: 66288000000,
operatingIncomeRatio: 0.241473143544069,
totalOtherIncomeExpensesNet: 803000000,
incomeBeforeTax: 67091000000,
incomeBeforeTaxRatio: 0.244398302460703,
incomeTaxExpense: 9680000000,
netIncome: 57411000000,
netIncomeRatio: 0.209136112780722,
eps: 3.31,
epsdiluted: 3.28,
weightedAverageShsOut: 17352119000,
weightedAverageShsOutDil: 17528214000,
link: "https://www.sec.gov/Archives/edgar/data/320193/000032019320000096/0000320193-20-000096-index.htm",
finalLink: "https://www.sec.gov/Archives/edgar/data/320193/000032019320000096/aapl-20200926.htm"
},
lb3vh1jj

lb3vh1jj1#

试试这个(我认为这可以帮助你循环键,值)

{% for key, value in apiList.iteritems() %}
wvyml7n5

wvyml7n52#

对我来说,这起了作用:

{% for key, value in apiList.items %}

相关问题