【问题标题】:Getting data from Django models to Google Charts从 Django 模型获取数据到 Google Charts
【发布时间】:2021-08-11 03:03:00
【问题描述】:

我正在尝试显示商店中最畅销商品的图表。所以我需要从数据库中获取信息并进入 html。图表似乎没有加载。当我尝试静态数据(来自 Google 的示例)时,它工作正常。但是,我似乎无法使用动态数据来做到这一点。我将数组转换为 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>

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

【问题讨论】:

    标签: javascript python json django google-visualization


    【解决方案1】:

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

    这是工作配置:

      // 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]
      ]);
    

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

    注意:您有 0 的值,因此,如果所有值都为零,则不会有图表 生成,在您的样本数据中,只有 1 coffe 的值更大 大于零:

        ['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" />

    【讨论】:

      【解决方案2】:

      在views.py中

      def send_data(request):
          # get data ...
          # convert to dual items in tuple, dictionary, list & etc...
          return render(request, 'template_name', context={'data':data})
      

      在javascript文件中

      const draw_chart = (data) => {
          // draw chart....
      }
      
      

      在模板 html 文件中

      <script>
          draw_chart({{ data }})
      </script>
      

      【讨论】:

        猜你喜欢
        • 2020-09-19
        • 1970-01-01
        • 2022-11-27
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-11
        • 2021-12-16
        相关资源
        最近更新 更多