如何遍历SQL数据并使用ChartJS绘制图形?

时间:2019-01-06 18:27:33

标签: javascript python chart.js bottle

这是我数据的一小部分

| Firm       | Product     | Sales        |
|:-----------|------------:|:------------:|
| A          |        TV1  |     This     |
| A          |        TV2  |    column    |
| B          |        TV3  |     will     |
| C          |        TV4  |      be      |
| C          |        TV5  |    number    |

我想使用ChartJS和bottle / Flask制作这样的图形

https://i.imgur.com/Nw09P4A.jpg

bottle.py中的代码:

c.execute("SELECT DISTINCT Firm FROM database")
result1 = c.fetchall()
firms=[j[0] for j in result1]
c.execute("SELECT * FROM database")
database = c.fetchall()

JavaScript代码:

 data: {
    labels: [
        % for firm in firms:
        '{{ firm[0] }}',
        %end        
    ],
    datasets: [
        % for item in database:
        {
        label: '{{ item[1] }}',
            %if '{{ item[0] }}' == 'A':
                data: [{{ item[2] }},null,null],
                backgroundColor: "#0e7a0d"
            elif '{{ item[0] }}' == 'B':   
                data: [null,{{ item[2] }},null],
                backgroundColor: "##e4000f"
            else:
                data: [null,null ,{{ item[2] }}],
                backgroundColor: "#003791"
            %end 
        },
        %end 
    ]

但是它只显示一个空的画布。

编辑:要获得如下结果:

data: {
labels: ["A", "B", "C"],
datasets: [{
  label: 'TV1',
  backgroundColor: "rgba(153,255,51,1)",
  data: [10, 0, 0],
}, {
  label: 'TV2',
  backgroundColor: "rgba(255,153,0,1)",
  data: [0,30, 0],
  }]
 }

我应该使用这样的Js代码:

        %if  item[0]  == 'A':
            data: [{{ item[2] }},null,null],
            backgroundColor: "#0e7a0d"
        elif  item[0]  == 'B':   
            data: [null,{{ item[2] }},null],
            backgroundColor: "##e4000f"
        else:
            data: [null,null ,{{ item[2] }}],
            backgroundColor: "#003791"
        %end    

0 个答案:

没有答案