INDEX 只从数据库中拉取一行数据

INDEX only pulling one row of data from database

我这辈子都无法让索引页正确显示数据库中的数据。我尝试了多种方法并在多个网站上进行了研究。我在想它就在我面前,但现在我无法透过树木看到森林。我在下面包含了我的代码。

申请:

@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 现在生成的屏幕截图:

以及我数据库中的数据table:

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

symbol 具有 for symbol in stocks: 的最后一次迭代的值。看起来 html 应该从 stock ({% for stock in stocks %}) 而不是 symbol.

创建 td 元素

简化建议:

在 .py 的 for symbol in stocks: 循环中,为价格的 symbol 字典添加一个键。这将使 quotes 对象变得不必要,并且 stocks 列表将是自包含的。