【发布时间】: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