INDEX仅从数据库中提取一行数据

问题描述

在我生命中,我无法获取索引页来正确显示数据库中的数据。我在多个站点上尝试了多种方法和研究。我想这是摆在我面前的东西,但是现在我看不到穿过树林的森林。我在下面包含了我的代码

应用程序:

@app.route("/")
@login_required
def index():

    users = db.execute("SELECT * FROM users WHERE id = :user_id",user_id=session["user_id"])
    stocks = db.execute("SELECT * FROM transactions WHERE id = :user_id",user_id=session["user_id"])
    quotes = {}

    for symbol in stocks:
        quotes[symbol["symbol"]] = lookup(symbol["symbol"])

    return render_template ("index.html",quotes=quotes,stocks=stocks,symbol=symbol)

index.html:

{% extends "layout.html" %}

{% block title %}
    Portfolio
{% endblock %}

{% block main %}
    <table class="table table-striped">
        <tr>
            <th> Symbol</th>
            <th> Current Share Price</th>
            <th> Shares Owned</th>
            <th> Shares Owned Value</th>
        </tr>

        {% for stock in stocks %}
        <tr>
            <td>{{symbol.symbol}}</td>
             <td>{{quotes[stock.symbol]["price"] | usd }}</td>
            <td>{{symbol.shares}}</td>
            <td>{{symbol.total_price}}</td>
        </tr>
        {% endfor %}

    </table>
{% endblock %}

最后,这是现在生成的index.html的屏幕截图:

index

还有我数据库表中的数据:

enter image description here

如您所见,该表仅显示其中一项交易的代码,股票和总价。它显示了每种股票的正确更新价格,但我无法从表中获取正确的数据。非常感谢您的帮助。

解决方法

symbol具有for symbol in stocks:的最后一次迭代的值。似乎html应该从stock{% for stock in stocks %})而不是symbol创建td元素。

建议简化:

在.py的for symbol in stocks:循环中,将一个密钥添加到symbol字典中以获取价格。这将使quotes对象变得不必要,并且stocks列表将是独立的。