Bokeh折线图无法显示:按月年组合展示商品均价问题求助
Django折线图年月组合维度失效排查方案
核心问题定位
终端有数据但前端图表空白,说明后端数据生成正常,但数据格式与前端图表配置不匹配,或年月组合的分组/传递环节存在问题。以下分模块逐一排查:
1. 后端视图:确认年月组合的数据结构与输出格式
假设你的商品价格模型类似:
class PriceRecord(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) avg_price = models.DecimalField(max_digits=10, decimal_places=2) record_date = models.DateField()
错误排查点:
- 分组逻辑错误:若手动拼接年月(如
Concat(ExtractMonth('record_date'), Value('/'), ExtractYear('record_date'))),需确保分组依据正确,避免因类型不匹配导致聚合失败。推荐使用TruncMonth函数直接生成年月时间对象,再转换为前端需要的字符串格式:from django.db.models import Avg from django.db.models.functions import TruncMonth def monthly_avg_view(request, product_id): # 按月份聚合数据 aggregated_data = PriceRecord.objects.filter(product_id=product_id).annotate( month_period=TruncMonth('record_date') ).values('month_period').annotate(avg_price=Avg('avg_price')).order_by('month_period') # 转换为前端可识别的年月字符串(如"6/2023") labels = [item['month_period'].strftime("%m/%Y").lstrip('0') for item in aggregated_data] data = [float(item['avg_price']) for item in aggregated_data] # 验证终端输出的labels和data是否非空且格式正确 print(labels, data) return JsonResponse({'labels': labels, 'data': data}) - JSON输出结构:确保返回的JSON包含
labels和data两个字段,且字段名与前端完全一致(注意大小写)。直接在浏览器访问视图URL,查看返回的JSON是否符合预期:{"labels": ["6/2023", "7/2023"], "data": [120.5, 135.2]}
2. 前端模板:调整图表x轴配置适配分类数据
单独用年/月(数值类型)时图表正常,是因为默认x轴为linear类型;但年月组合是字符串分类,必须修改x轴类型为category,否则图表无法解析。以Chart.js为例:
<canvas id="priceLineChart"></canvas> <script> fetch('{% url "monthly_avg_view" product.id %}') .then(res => res.json()) .then(result => { const ctx = document.getElementById('priceLineChart').getContext('2d'); new Chart(ctx, { type: 'line', data: { labels: result.labels, datasets: [{ label: '月度均价', data: result.data, borderColor: '#2196F3', fill: false }] }, options: { scales: { x: { type: 'category', // 关键:必须设置为分类类型 title: { display: true, text: '年月' } }, y: { title: { display: true, text: '均价' } } } } }); }) .catch(err => console.log('数据加载失败:', err)); </script>
前端额外排查:
- 打开浏览器开发者工具(F12)→ Console标签,查看是否有JS报错:
- 若提示
result.labels is undefined:检查后端返回的JSON字段名是否与前端一致; - 若提示数据类型错误:确认后端返回的
data是数值类型(而非字符串)。
- 若提示
- 若数据为空数组:检查视图中过滤条件是否正确(如商品ID是否传对、是否有对应时间段的数据)。
3. 模型层:确认日期字段完整性
确保record_date字段不为空,且所有数据都包含有效的年/月信息,避免因部分数据缺失导致聚合后年月标签不连续或为空。
内容的提问来源于stack exchange,提问作者developer
相关产品推荐
相关产品推荐

