例如,我有資料庫
| ID | 帳戶ID | 日期 |
|---|---|---|
| 1 | 127 | 2022-04-25 |
| 2 | 128 | 2022-04-25 |
| 3 | 127 | 2022-04-24 |
| 4 | 128 | 2022-04-24 |
我需要在 2 個不同的桌子上分開這個:
| 帳戶ID | 日期標題 |
|---|---|
| 127 | 2022-04-25 |
| 127 | 2022-04-24 |
和 128 一樣
這是我的 1 個表的代碼,我不知道如何分開
@bp.route('/')
def main():
wcms = Wcm.query.order_by(Wcm.date.desc()).all()
return render_template('table.html', wcms=wcms)
HTML:
<table class="table table-hover table-dark wcm">
<thead>
<tr>
<th>Date</th>
<th>WCM account ID</th>
<th>Number of standard tags</th>
<th>Number of extended tags</th>
</tr>
</thead>
<tbody>
{% for wcm in wcms %}
<tr>
<td>{{ wcm.date }}</td>
<td>{{ wcm.account_id }}</td>
<td>{{ wcm.nbm_stardart_tags }}</td>
<td>{{ wcm.nbm_custom_tags }}</td>
</tr>
{% endfor %}
</tbody>
</table>
uj5u.com熱心網友回復:
為了使以下代碼正常作業,我們需要首先按分組值對資料進行排序。由于您想要單獨的帳戶 ID,因此我選擇了 ASC。
wcms = Wcm.query.order_by(Wcm.account_id.asc(), Wcm.date.desc()).all()
lambda 回傳帳戶 ID 以將所有條目收集到一個串列中。groupby回傳 a listof tuples,list()需要呼叫來評估創建組的惰性迭代器。外部串列推導創建了這些分組 Wcm 串列的串列。
wcms_by_account = [
list(wcm_group)
for acc_id, wcm_group
in groupby(wcms, lambda x: x.account_id
]
串列結構:
[
[
Wcm(account_id=127, date=2022-04-25, ...),
Wcm(account_id=127, date=2022-04-24, ...),
],
[
Wcm(account_id=128, date=2022-04-25, ...),
Wcm(account_id=128, date=2022-04-24, ...),
],
...
]
然后更改您的 Web 模板以處理串列串列,為每個內部串列創建一個新表。
{% for wcms in wcms_by_account %}
<table class="table table-hover table-dark wcm">
<thead>
<tr>
<th>Date</th>
<th>WCM account ID</th>
<th>Number of standard tags</th>
<th>Number of extended tags</th>
</tr>
</thead>
<tbody>
{% for wcm in wcms %}
<tr>
<td>{{ wcm.date }}</td>
<td>{{ wcm.account_id }}</td>
<td>{{ wcm.nbm_stardart_tags }}</td>
<td>{{ wcm.nbm_custom_tags }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endfor %}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/463886.html
