今天將數字變成圖表,讓使用者知道自己的收藏主要集中在哪些分類。
步驟 1:在 stats() 中取得分類資料
在 app.py 的 stats() 中,加入以下查詢,位置放在 connection.close() 之前:
movie_genres = connection.execute(""" SELECT COALESCE(NULLIF(genre, ''), '未分類') AS label, COUNT() AS total FROM media WHERE media_type = 'movie' GROUP BY COALESCE(NULLIF(genre, ''), '未分類') ORDER BY total DESC""").fetchall()game_statuses = connection.execute(""" SELECT status AS label, COUNT() AS total FROM media WHERE media_type = 'game' GROUP BY status ORDER BY total DESC""").fetchall()
接著在 render_template() 裡加入:
movie_genres=[ {"label": row["label"], "total": row["total"]} for row in movie_genres],game_statuses=[ {"label": row["label"], "total": row["total"]} for row in game_statuses]
步驟 2:在 stats.html 加入圖表區域
在統計卡片後面加入:
步驟 3:加入 Chart.js
在 stats.html 最後一個 {% block content %} 內,圖表區域後加入:
這裡的 tojson 會把 Python 傳入的資料轉成 JavaScript 能讀取的 JSON 格式,避免直接用字串拼接資料。
步驟 4:測試