javascript - 从 Django 模型获取数据到 Google Charts

标签 javascript python json django google-visualization

我正在尝试显示商店中最畅销商品的图表。所以我需要从数据库中获取信息并将其放入 html 中。图表似乎无法加载。当我尝试静态数据(来自谷歌的例子)时,它工作正常。但是,我似乎无法使用动态数据来做到这一点。我将数组转换为 json 并在 html 中执行 |safe 进行转义。然而它仍然没有出现。如果有人有关于如何修复它的提示,请帮助!

下面是我的 views.py,我在其中调用包含图表脚本的 html 文件。

def charts(request):
    data_arr = []
    for item in Item.objects.all():
        data_arr.append([item.ItemName, item.quantity_sold])
    return render(request,'coffeeapp/charts.html',{'item':json.dumps(data_arr)})

这是我在 charts.html 文件中的代码

<script src="https://www.gstatic.com/charts/loader.js"></script>
    <script>
        google.charts.load('current', { packages: ['corechart'] });
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {
            // Define the chart to be drawn.
            var data = google.visualization.arrayToDataTable(
                ['Item', 'Quantity Sold'],
                [{{item|safe}}]
            );
            
            // Instantiate and draw the chart.
            var chart = new google.visualization.PieChart(document.getElementById('myPieChart'));
            chart.draw(data, null);
        }
    </script>

    <!--Div that will hold the pie chart-->
    <div id="myPieChart"/>

编辑 1:{{item|safe}} 中的内容

我已经在 views.py 中打印了项目,结果是这样的:

[["Espresso", 0], ["Cappuccino", 2], ["Black Coffee", 0], ["Cafe Latte", 0], ["Mocha", 0], ["Iced Americano", 0]....

在浏览器/html 中,我添加了 alert({{item|safe}}) 作为 function drawChart() 下的第一行,它显示从我所看到的准确的项目。 部分结果如下

Espresso,0,Cappuccino,2,Black Coffee,0,Cafe Latte,0,Mocha,0,Iced Americano,0,Iced Caramel Macchiato,0,Cold Brew,0....

编辑 2 - 解决方案

在 Marco 的回答的帮助下,我解决了这个问题。 Marco 有修复标签的答案,但数据行是静态的,意味着手动输入,而我想从数据库中获取它。 因此,我修改了我的观点。

def charts(request):
    return render(request,'coffeeapp/charts.html',{'item':Item.objects.all()})

我的 html 是:

<script src="https://www.gstatic.com/charts/loader.js"></script>
    <script>
        google.charts.load('current', { packages: ['corechart'] });
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {
            // Define the chart to be drawn.
            
        var data = google.visualization.arrayToDataTable([
            [{ label: 'Item', type: 'string' },
            { label: 'Quantity Sold', type: 'number' }],
            {% for i in item %}
                ['{{ i.ItemName }}', {{ i.quantity_sold }}],
            {% endfor %}
        ]);
        var options = {
            'title': 'MOST ORDERED DRINKS',
            'width': 700,
            'height': 700
        };
        // Instantiate and draw the chart.
        var chart = new google.visualization.PieChart(document.getElementById('myPieChart'));
        chart.draw(data, options);
        }

    </script>

我不确定它是如何工作的,但它没有 safe 关键字。

最佳答案

仔细检查您的图表设置 - 似乎您需要更多设置来创建饼图标签。

这是工作配置:

  // Define the chart to be drawn.
  // Data settings = modified for generate the Pie Chart: 
  var data = google.visualization.arrayToDataTable([
    [{label: 'Item', type: 'string'}, 
     {label: 'Quantity Sold', type: 'number'}],
    ['Espresso', 0],
    ['Cappuccino', 2],
    ['Black Coffee', 0],
    ['Cafe Latte', 0],
    ['Mocha', 0],
    ['Iced Americano', 0],
    ['Iced Caramel Macchiato', 0],
    ['Cold Brew', 0]
  ]);

根据您在问题中提供的信息,我修改了代码并看到了生成的图表。

N.B: you have values with 0, so, if all values are zero, no chart will be generated, in your sample data, only 1 coffe has a value greater than zero:

    ['Cappuccino', 2], // This is the value that will show in the chart.

这是 working jsfiddle .

google.charts.load('current', {
  packages: ['corechart']
});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  // Define the chart to be drawn.
  // Data settings = modified for generate the Pie Chart: 
  var data = google.visualization.arrayToDataTable([
    [{
        label: 'Item',
        type: 'string'
      },
      {
        label: 'Quantity Sold',
        type: 'number'
      }
    ],
    ['Espresso', 0],
    ['Cappuccino', 2], // This is the value that will show in the chart.
    ['Black Coffee', 0],
    ['Cafe Latte', 0],
    ['Mocha', 0],
    ['Iced Americano', 0],
    ['Iced Caramel Macchiato', 0],
    ['Cold Brew', 0]
  ]);

  // Instantiate and draw the chart.
  var chart = new google.visualization.PieChart(document.getElementById('myPieChart'));
  chart.draw(data, null);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="myPieChart" />

关于javascript - 从 Django 模型获取数据到 Google Charts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67644426/

相关文章:

javascript - 如何读取指针(local_tbb.dwData)处的内存以获取窗口句柄

javascript - JQuery .html() 方法和 Javascript .innerHTML = "<div> somediv </div>"之间的区别?

javascript - 每行动态设置值时,Extjs 6 组合框值和显示值无法正确显示

javascript - React.js : How to run window. open() 连续多次?

java - 异步类无法打印出 JSON 提要的内容

c# - JSON 添加节点到现有的 JObject

javascript - 查找输入位置和附近位置的商店并计算它们与搜索位置的距离

python - 为什么装饰类会丢失其文档字符串?

python - 删除子字符串时结果中没有双倍空格的最佳正则表达式(在 Python 中)?

javascript - 静态网页和共享同一 TLD 的谷歌应用引擎服务器之间的 AJAX