Python 试图在Jinja2模板中查找列表的总和

Python 试图在Jinja2模板中查找列表的总和,python,flask,jinja2,flask-sqlalchemy,Python,Flask,Jinja2,Flask Sqlalchemy,我有一个烧瓶应用程序,需要显示投资者的总投资。有三种模式,即基金、投资者和投资,其定义如下: 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)

我有一个烧瓶应用程序,需要显示投资者的总投资。有三种模式,即基金、投资者和投资,其定义如下:

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) 
{% 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 %}
最后,我的模板Investors.html如下所示:

@app.route("/Investors", methods=['GET','POST'])
def Investors():
    Investors = Investor.query.all()
    return render_template('Investors.html', title="List of Investors", investors=Investors) 
{% 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 %}
{%extends“layout.html”%}
{%block content%}
投资者名单
名称 电子邮件 总投资价值 {投资者占投资者的百分比%} {{investor.email} {{投资者.基金|价值|总和} {%endfor%}
{%endblock%}

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

您应该在视图中使用这种逻辑,或者创建一个类方法

以下是更新视图的方法:

@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在模板中引用投资金额。

基金价值是一种关系,而不是一列。你确定你能计算吗?你测试过它是数字列吗?如果一切正常,那么您有许多可选项,比如在渲染之前在sl查询或python中计算总和。这是“商业”逻辑。在视图中保留这样的逻辑,而不是在模板中,这样你会更快乐。同样,这确实是一个干净的解决方案,并且可以按预期工作。但是出于好奇,您不认为模板中的一行代码比路由中的逻辑要好吗。我同意@DaveW.Smith的评论,即这是业务逻辑,应该保留在视图中。