You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中如何提取数据库Close字段结合Chart.js绘制柱状图

实现步骤

1. 从数据库提取Close字段转为列表

你可以根据自己使用的后端技术栈选择对应实现,以下给出两种常用场景的示例:

Python 场景(以Sqlite+Pandas为例,其他数据库/ORM框架逻辑一致)

import pandas as pd
import sqlite3

# 连接数据库
conn = sqlite3.connect('替换为你的数据库文件路径.db')
# 查询指定字段
df = pd.read_sql("SELECT Close, Time FROM 替换为你的表名", conn)
# 单独提取Close字段转为列表
close_list = df['Close'].tolist()
# 可同时提取时间作为X轴标签
time_labels = df['Time'].tolist()
# 关闭连接
conn.close()

Node.js 场景(以Mysql为例)

const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: '替换为你的数据库用户名',
  password: '替换为你的数据库密码',
  database: '替换为你的库名'
});

let closeList = [];
let timeLabels = [];
connection.query('SELECT Close, Time FROM 替换为你的表名', function (error, results) {
  if (error) throw error;
  closeList = results.map(item => item.Close);
  timeLabels = results.map(item => item.Time);
  // 可在此处返回数据给前端,或直接初始化图表
});
connection.end();

2. 用Chart.js渲染柱状图

你已经有Chart.js的使用经验,只需把之前的随机测试数据替换为上面拿到的closeList即可,示例代码如下:

页面结构

<!-- 图表容器 -->
<canvas id="closeBarChart" width="600" height="300"></canvas>

图表初始化逻辑

// 此处的closeList、timeLabels替换为你从数据库拿到的实际数据
const closeList = [38735, 38727, 38739, 38750, 38730, 38723];
const timeLabels = ["2:22 p.m.", "2:23 p.m.", "2:24 p.m.", "2:25 p.m.", "2:26 p.m.", "2:27 p.m."];

const ctx = document.getElementById('closeBarChart').getContext('2d');
new Chart(ctx, {
  type: 'bar',
  data: {
    labels: timeLabels,
    datasets: [{
      label: 'Close数值',
      data: closeList,
      backgroundColor: 'rgba(75, 192, 192, 0.6)',
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      y: {
        beginAtZero: false // Close值区间集中,无需从0开始,展示更清晰
      }
    }
  }
});

注意事项

  • 前后端分离项目中,后端可以把提取到的列表封装为JSON接口返回,前端通过fetch/axios请求获取数据后再初始化图表即可
  • 注意SQL语句中的字段名、表名要和实际数据库中的命名保持一致,避免大小写导致的取值错误
  • 数据量较大时建议先做聚合处理再渲染,避免图表加载卡顿

内容的提问来源于stack exchange,提问作者ashish gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 21:54:06