我有兩個表:FundingSource()和AllocationSummary()。我正在使用外鍵,因為這兩個表之間存在一對多的關系——一個資金來源可以有多個分配,但一個分配只能有一個資金來源。
這是我的兩張桌子:
class FundingSource(db.Model):
id = db.Column(db.Integer, primary_key=True)
complete = db.Column(db.String(10), default=False, nullable=False)
department = db.Column(db.String(100), nullable=False)
agency = db.Column(db.String(150), nullable=False)
funding_source = db.Column(db.String(200), nullable=False)
bill = db.Column(db.String(10), nullable=False)
allocations = db.relationship('AllocationSummary', backref='allocation', lazy=True)
class AllocationSummary(db.Model):
id = db.Column(db.Integer, primary_key=True)
state = db.Column(db.String(100), nullable=False)
eligible_applicant = db.Column(db.String(100), nullable=False)
recipient = db.Column(db.String(200), nullable=False)
amount = db.Column(db.Float(), nullable=False)
funding_source_id = db.Column(db.Integer, db.ForeignKey('funding_source.id'), nullable=False)
我有一個網頁分配摘要,<table>如下所示:
我的問題是,如何使用外鍵從 FundingSource() 表中呼叫 id、agency 和funding_source 屬性?我需要使用該表中的這些屬性獲取/查詢“Agency”和“Fund”列的值,如上圖所示,并使用 AllocationSummary() 表中的屬性獲取其余列值.
這是我的 .py 檔案:
@main.route("/allocationSummary")
def alloc_summ():
all_data2 = AllocationSummary.query.filter(AllocationSummary.funding_source_id == FundingSource.id).all()
return render_template('allocationSummary.html', title='Allocation Summary', allocs=all_data2)
這是我的 HTML 檔案:
....
<tbody>
{% for row in allocs%}
<tr>
<td>{{ row.id }}</td>
<td>{{ row.complete }}</td>
<td>{{ row.agency }}</td>
<td>{{ row.funding_source }}</td>
<td>{{ row.bill }}</td>
<td>{{ row.state }}</td>
<td>{{ row.eligible_applicant }}</td>
<td>{{ row.recipient }}</td>
<td>{{ row.amount }}</td>
</tr>
{% endfor %}
</tbody>
....
我似乎無法找到一種方法來一次使用 2 個不同表中的屬性進行查詢以顯示在我的表中。任何幫助將不勝感激!
uj5u.com熱心網友回復:
您已經backref在db.relationship中定義了 aFundingSource但allocation我不會呼叫它,foundingsource因為這將是Allocation. 使用該成員,您可以像這樣訪問該員工的資料FoundingSource:
....
<tbody>
{% for row in allocs%}
<tr>
<td>{{ row.id }}</td>
<td>{{ row.foundingsource.complete }}</td>
<td>{{ row.foundingsource.agency }}</td>
<td>{{ row.foundingsource.funding_source }}</td>
<td>{{ row.foundingsource.bill }}</td>
<td>{{ row.state }}</td>
<td>{{ row.eligible_applicant }}</td>
<td>{{ row.recipient }}</td>
<td>{{ row.amount }}</td>
</tr>
{% endfor %}
</tbody>
....
這將是關系的定義:
allocations = db.relationship('AllocationSummary', backref='foundingsource', lazy=True)
因為這backref是將添加到關系的相應類中的成員的名稱。
一對多 SQLAlchemy
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/420243.html
標籤:
