【问题标题】:Trying to find sum of a list in a Jinja2 template试图在 Jinja2 模板中查找列表的总和
【发布时间】:2020-12-04 18:49:22
【问题描述】:

我有一个烧瓶应用程序,我需要在其中显示投资者的总投资。共有 3 种模型,即 Fund、Investor 和 Investments,它们被定义为:

class Fund(db.Model):
    FundID = db.Column(db.Integer, primary_key=True)
    FundName = db.Column(db.String(50), unique=True, nullable=False)
    UnitPrice = db.Column(db.Float)

    def __repr__(self):
        return f"Fund('{self.FundName}', '{self.UnitPrice}')"

class Investor(db.Model):
    InvestorID = db.Column(db.Integer, primary_key=True)
    FirstName = db.Column(db.String(20), nullable=False)
    LastName = db.Column(db.String(20), nullable=False)
    email = db.Column(db.String(100), unique=True, nullable=False)
    fund_value = db.relationship('Investment', backref='Investor')
    
    def __repr__(self):
        return f"Investor('{self.InvestorID}','{self.FirstName}')"


class Investment(db.Model):
    InvestmentID = db.Column(db.Integer, primary_key=True)
    Fund_ID = db.Column(db.Integer, db.ForeignKey('fund.FundID'), nullable=False)
    Investor_ID = db.Column(db.Integer, db.ForeignKey('investor.InvestorID'), nullable=False)
    Units = db.Column(db.Integer, nullable=False)
    Investment_Value = db.Column(db.Integer)
    
    def __repr__(self):
        return f'{self.Investment_Value}'

我的投资者页面路径如下:

@app.route("/Investors", methods=['GET','POST'])
def Investors():
    Investors = Investor.query.all()
    return render_template('Investors.html', title="List of Investors", investors=Investors) 

最后,我的模板 Investors.html 如下:

{% extends "layout.html" %}
{% block content %}
        <h1>List of Investors</h1><br/>
        <table>
        <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Total Investment Value</th>
        </tr>
        {% for investor in investors %}        
                <tr>
                  <td><a class="mr-2" href="{{ url_for('update_investor', Investor_ID=investor.InvestorID) }}">{{ investor.FirstName }} {{ investor.LastName }}</a></td>
                  <td>{{ investor.email }}</td>
                  <td>{{ investor.fund_value|sum }}</td>
                </tr>
        {% endfor %}
        </table><br/>
        <div>
          <a class="btn btn-info" href="{{ url_for('create_investor') }}">Add New Investor</a>
        </div>        
{% endblock %}

现在,在这个模板中,在最后一个 td 中,我试图找到特定投资者的所有投资的总和并显示它,但是当我使用 {{investor.fund_value|sum }} 时,它给了我错误“TypeError:+:'int'和'Investment'不支持的操作数类型”。我通过在我的 Jinja 模板中运行一个循环来尝试这个,但没有帮助。由于我是 Flask 的新手,所以我在这里被困了一段时间,因此感谢您的帮助。

【问题讨论】:

  • fund_value 是关系而不是列。你确定你可以计算它吗?您是否测试过它是数字列?如果一切正常,你有很多选择,比如在 sl 查询中或在渲染之前在 python 中计算总和

标签: python flask jinja2 flask-sqlalchemy


【解决方案1】:

您应该将这种逻辑带到视图中,或者创建一个类方法。

以下是更新视图的方法:

@app.route("/Investors", methods=['GET','POST'])
def Investors():
    Investors = Investor.query.all()

    invested_sums = {}
    for investor in Investors:
        invested_sums[investor.InvestorID] = 0
        investments_by_investor = Investment.query.filter_by(Investor_ID=investor.InvestorID)
        for investment in investments_by_investor:
            invested_sums[investor.InvestorID] += investment.Investment_Value

    return render_template('Investors.html', title="List of Investors", investors=Investors, invested_sums=invested_sums)

然后您可以通过 InvestorID 参考您模板中的投资金额。

【讨论】:

  • 同意。这是“商业”逻辑。将这样的逻辑保留在视图中,而不是模板中,您会更快乐。
  • 也同意,这确实是干净的解决方案,并且按预期工作。但是只是出于好奇,你不觉得模板中的一行代码比路由中的这个逻辑要好。我同意@DaveW.Smith 的评论,即它的业务逻辑应该保留在视图中。
猜你喜欢
  • 2017-06-07
  • 1970-01-01
  • 2022-12-05
  • 2020-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-24
  • 2021-05-28
相关资源
最近更新 更多