本文以「水井村特色商品智慧銷售平台」為情境,示範如何將顧客、商品、訂單與訂單明細資料轉換成可自動更新的行銷洞察。每當新增一筆已完成訂單,系統便重新計算顧客總消費、購買次數、平均客單價、最近購買日期、回購狀態、商品偏好及顧客分群,並在 Dashboard 顯示行銷建議。
圖 1 智慧銷售平台教學文章與分析儀表板整體示意
圖片說明: 圖片呈現完整教學文章的視覺架構,包含地方特色商品情境、顧客與訂單資料表、分析結果、Django ORM 程式區塊,以及銷售趨勢、熱銷商品、顧客分群與行銷建議等 Dashboard 元件。可作為文章首圖或社群分享圖。
一、先定義「自動分析」要回答的問題
智慧銷售平台不應只是一個商品展示網站,而要能協助經營者回答具體的行銷問題:
哪些顧客的累積消費金額最高?
哪些顧客曾再次購買,整體回購率是多少?
哪些商品最熱銷,哪些商品分類最受偏好?
哪些顧客已長時間未消費,需要啟動喚回活動?
應該對不同顧客提供什麼優惠或推薦?
交易資料 → Django ORM 彙整 →
行為指標 → 顧客分群 →
Dashboard → 行銷建議
二、範例情境與資料
平台可銷售水井姻緣花、玉米籜金魚、在地農產禮盒、水井村導覽體驗券與智慧農業體驗課程。課堂實作建議至少準備 10 位顧客、8 項商品、30 筆訂單與 50 筆訂單明細。
顧客資料
顧客編號 姓名 加入日期
C001 王小明 2026-01-10
C002 李小華 2026-02-15
C003 陳美玲 2026-03-20
商品資料
商品編號 商品名稱 分類 單價
P001 水井姻緣花 文創商品 350 元
P002 玉米籜金魚 永續工藝 250 元
P003 農產禮盒 在地農產 600 元
P004 水井村導覽券 體驗活動 300 元
三、Django 資料模型
最小可行版本使用四個模型:Customer 、Product 、Order 、OrderItem 。顧客與商品的購買關係,透過訂單與訂單明細串接。
程式碼 1 核心資料模型(models.py)
from decimal import Decimal
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
category = models.CharField(max_length=50)
price = models.DecimalField(max_digits=10, decimal_places=2)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.name
class Customer(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(blank=True)
joined_at = models.DateField(auto_now_add=True)
def __str__(self):
return self.name
class Order(models.Model):
STATUS_CHOICES = [
("pending", "待處理"),
("completed", "已完成"),
("cancelled", "已取消"),
]
customer = models.ForeignKey(
Customer, on_delete=models.CASCADE, related_name="orders"
)
ordered_at = models.DateTimeField(auto_now_add=True)
status = models.CharField(
max_length=20, choices=STATUS_CHOICES, default="completed"
)
@property
def total_amount(self):
return sum(
(item.subtotal for item in self.items.all()),
Decimal("0.00")
)
class OrderItem(models.Model):
order = models.ForeignKey(
Order, on_delete=models.CASCADE, related_name="items"
)
product = models.ForeignKey(
Product, on_delete=models.PROTECT, related_name="order_items"
)
quantity = models.PositiveIntegerField(default=1)
unit_price = models.DecimalField(max_digits=10, decimal_places=2)
@property
def subtotal(self):
return self.unit_price * self.quantity
程式碼說明: 訂單價格應保存當下的 unit_price ,避免商品日後調價時改變歷史交易。分析時只納入狀態為 completed 的有效訂單。
四、建立顧客購買行為指標
指標 計算方式 行銷用途
總消費金額 有效訂單明細小計加總 辨識高價值顧客
購買次數 有效訂單數 判斷回購與忠誠度
平均客單價 總消費金額 ÷ 購買次數 規劃滿額優惠與組合銷售
最近購買日期 有效訂單日期最大值 辨識沉睡或流失風險
回購率 購買兩次以上顧客數 ÷ 購買顧客總數 評估會員經營成效
程式碼 2 使用 Django ORM 彙整顧客行為(services.py)
from decimal import Decimal
from django.db.models import (
Count, DecimalField, ExpressionWrapper,
F, Max, Q, Sum, Value
)
from django.db.models.functions import Coalesce
from .models import Customer
def get_customer_analysis():
completed = Q(orders__status="completed")
item_total = ExpressionWrapper(
F("orders__items__quantity")
* F("orders__items__unit_price"),
output_field=DecimalField(
max_digits=12, decimal_places=2
),
)
return Customer.objects.annotate(
total_spending=Coalesce(
Sum(item_total, filter=completed),
Value(
Decimal("0.00"),
output_field=DecimalField(
max_digits=12, decimal_places=2
),
),
),
purchase_count=Count(
"orders", filter=completed, distinct=True
),
last_purchase=Max(
"orders__ordered_at", filter=completed
),
).order_by("-total_spending")
程式碼說明: annotate() 會將每位顧客的分析結果附加到查詢物件上;Coalesce() 可把沒有消費紀錄時的 NULL 轉為 0;distinct=True 可避免訂單因多筆明細而被重複計數。
五、顧客自動分群
初學課程可先使用規則式分群,不必立即導入機器學習。判斷順序要明確,避免同一位顧客同時落入多個主要類型。
顧客類型 範例條件 建議策略
沉睡顧客 90 天以上未購買 發送限期喚回優惠
高價值顧客 總消費達 1,000 元以上 VIP 服務、新品優先通知
忠誠顧客 購買 3 次以上 會員集點、專屬活動
一般顧客 購買 2 次 推薦關聯商品
新顧客 購買 1 次 第二次購買優惠
潛在顧客 尚無購買紀錄 首次購買優惠
程式碼 3 顧客分類函式(services.py)
from decimal import Decimal
from django.utils import timezone
def classify_customer(customer):
inactive_days = None
if customer.last_purchase:
inactive_days = (
timezone.now() - customer.last_purchase
).days
if inactive_days is not None and inactive_days >= 90:
return "沉睡顧客"
if customer.total_spending >= Decimal("1000"):
return "高價值顧客"
if customer.purchase_count >= 3:
return "忠誠顧客"
if customer.purchase_count >= 2:
return "一般顧客"
if customer.purchase_count == 1:
return "新顧客"
return "潛在顧客"
六、自動產生行銷建議
程式碼 4 顧客類型對應行銷建議
def get_marketing_suggestion(customer_type):
suggestions = {
"新顧客": "提供第二次購買優惠,鼓勵完成首次回購。",
"一般顧客": "推薦相關商品組合,提高購買頻率。",
"忠誠顧客": "提供會員集點、專屬活動及新品通知。",
"高價值顧客": "提供 VIP 服務與新品優先購買。",
"沉睡顧客": "發送限期回購優惠,搭配過去偏好商品。",
"潛在顧客": "推薦熱門商品與首次購買優惠。",
}
return suggestions.get(
customer_type,
"持續觀察顧客購買行為。"
)
七、將分析結果傳給 Dashboard
程式碼 5 View 整合顧客分析結果(views.py)
from django.shortcuts import render
from .services import (
classify_customer,
get_customer_analysis,
get_marketing_suggestion,
)
def customer_analysis_dashboard(request):
customers = get_customer_analysis()
rows = []
for customer in customers:
customer_type = classify_customer(customer)
average_order_value = (
customer.total_spending / customer.purchase_count
if customer.purchase_count else 0
)
rows.append({
"customer": customer,
"total_spending": customer.total_spending,
"purchase_count": customer.purchase_count,
"average_order_value": average_order_value,
"last_purchase": customer.last_purchase,
"customer_type": customer_type,
"suggestion": get_marketing_suggestion(customer_type),
})
return render(
request,
"sales/customer_analysis.html",
{"analysis_rows": rows},
)
程式碼 6 顧客分析結果表格(customer_analysis.html)
<table class="table table-striped">
<thead>
<tr>
<th>顧客</th>
<th>總消費</th>
<th>購買次數</th>
<th>平均客單價</th>
<th>顧客類型</th>
<th>行銷建議</th>
</tr>
</thead>
<tbody>
{% for row in analysis_rows %}
<tr>
<td>{{ row.customer.name }}</td>
<td>{{ row.total_spending }}</td>
<td>{{ row.purchase_count }}</td>
<td>{{ row.average_order_value|floatformat:0 }}</td>
<td>{{ row.customer_type }}</td>
<td>{{ row.suggestion }}</td>
</tr>
{% endfor %}
</tbody>
</table>
圖 2 Django 智慧銷售平台自動分析教學資訊圖
圖片說明: 圖片由左至右呈現範例情境、顧客與訂單資料、Customer/Order/OrderItem/Product 關聯、前端 KPI 與圖表,以及 ORM 查詢、顧客分群程式與行銷應用。適合放在文章中段,協助讀者快速掌握「資料建模—分析—視覺化—決策」的完整流程。
八、Dashboard 應呈現哪些資訊?
建議至少包含四張 KPI 卡、三張圖表與三類顧客名單:
KPI: 總銷售額、訂單數、平均客單價、回購率。
圖表: 每月銷售趨勢、熱銷商品排行、顧客分群比例。
名單: 高價值顧客、忠誠顧客、沉睡顧客。
程式碼 7 Chart.js 熱銷商品長條圖
<canvas id="topProductsChart"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById("topProductsChart");
new Chart(ctx, {
type: "bar",
data: {
labels: {{ product_labels|safe }},
datasets: [{
label: "銷售數量",
data: {{ product_values|safe }}
}]
},
options: {
responsive: true,
indexAxis: "y",
plugins: {
legend: { display: false }
}
}
});
</script>
九、Vibe Coding 的課堂使用方式
學生可先用自然語言描述功能,再請生成式 AI 產生程式骨架,但必須自行驗證欄位、關聯、計算公式與錯誤處理。
提示詞範例:
請扮演 Django 開發工程師。我已有 Customer、Order 與 OrderItem 模型,請使用 Django ORM 計算每位顧客的總消費金額、有效訂單數、平均客單價及最近購買日期。分析邏輯放在 services.py,需排除 cancelled 訂單,並提供測試資料與預期結果。
十、課堂最低完成規格
商品、顧客、訂單與訂單明細管理。
總消費、購買次數、平均客單價、最近購買日期與回購率。
至少四種顧客類型的規則式分群。
至少三張分析圖表與一份顧客清單。
每類顧客至少一項自動行銷建議。
部署至 PythonAnywhere,新增訂單後分析結果能自動更新。
結語
這個範例的核心不是建立複雜的人工智慧模型,而是讓學生先理解:只要資料模型正確、指標定義清楚、查詢經過驗證,Django ORM 就能把日常交易資料轉換成具行銷價值的顧客洞察。完成規則式分析後,還可再延伸至 RFM、商品關聯分析、個人化推薦或生成式 AI 行銷文案。