一尘不染

通过JSON将Django数据库查询集传递给Highcharts

json

第一次海报,长期的读者。我花了很长时间寻找答案,这使我认为这是我所缺少的基本知识。

我试图提取保存在数据库表中的数据,并将其传递通过,以显示在Highcharts图中。在检查源代码时,我没有从Django或客户端收到任何错误。

使用:Django 1.7和Python 3.4

views.py:

#unit/views.py
from django.http import JsonResponse
from django.shortcuts import render
from unit.analysis_funcs import ChartData

def chart_data_json(request):
    data = {}
    data['chart_data'] = ChartData.get_data()
    return JsonResponse(data, safe = True)

def plot(request):    
    return render(request, 'unit/data_plot.html', {})

get_data()函数:

#unit/analysis_funcs.py
from unit.models import CheckValve

class ChartData(object):    
    def get_data():
        data = {'serial_numbers': [], 'mass': []}

        valves = CheckValve.objects.all()

        for unit in valves:
            data['serial_numbers'].append(unit.serial_number)
            data['mass'].append(unit.mass)

        return data

模板:

<!-- templates/unit/data_plot.html -->
{% extends "base.html" %}

{% block extrahead %}
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="http://code.highcharts.com/highcharts.js"></script>
{% endblock %}

{% block rootcontainer %}
    <div id="container" style="width:100%; height:400px;"></div>    
{% endblock %}

{% block overwrite %}
<!-- Overwrite the base.html jQuery load and put in head for Highcharts to work -->
{% endblock %}

{% block extrajs %}
<script>
$(document).ready(function() {

    var options = {
        chart: {
            renderTo: 'container',
            type: 'line'
        },
        series: [{}]
    };
    var ChartDataURL = "{% url 'chart_data_json' %}";
    $.getJSON('ChartDataURL', function(data) {
        options.xAxis.categories = data['chart_data']['serial_numbers'];
        options.series[0].name = 'Serial Numbers';
        options.series[0].data = data['chart_data']['mass'];
        var chart = new Highcharts.Chart(options);
    });

});
</script>
{% endblock %}

最后的网址:

from unit import views, graphs

urlpatterns = patterns('',

   url(r'^chart_data_json/', views.chart_data_json, name = 'chart_data_json'),

   url(r'^plot/', views.plot, name = 'plot'),

)

一切似乎都在运行,但Highchart图未渲染。我认为这是我将JSON数据从view.py移至template.html的方式,但是凝视了很久之后,我却cross之以鼻。

任何帮助都是极好的!


阅读 203

收藏
2020-07-27

共1个答案

一尘不染

我终于让我的绘图工作了。我在这里找到了这种方法。感谢Harrison发布他的方法!

我基于以上方法的新views.py:

def plot(request, chartID = 'chart_ID', chart_type = 'line', chart_height = 500):
    data = ChartData.check_valve_data()

    chart = {"renderTo": chartID, "type": chart_type, "height": chart_height,}  
    title = {"text": 'Check Valve Data'}
    xAxis = {"title": {"text": 'Serial Number'}, "categories": data['serial numbers']}
    yAxis = {"title": {"text": 'Data'}}
    series = [
        {"name": 'Mass (kg)', "data": data['mass']}, 
        {"name": 'Pressure Drop (psid)', "data": data['pressure drop']},
        {"name": 'Cracking Pressure (psid)', "data": data['cracking pressure']}
        ]

    return render(request, 'unit/data_plot.html', {'chartID': chartID, 'chart': chart,
                                                    'series': series, 'title': title, 
                                                    'xAxis': xAxis, 'yAxis': yAxis})

用于提取数据库对象和传递数据的快速功能:

class ChartData(object):    
    def check_valve_data():
        data = {'serial numbers': [], 'mass': [],
                 'pressure drop': [], 'cracking pressure': [], 'reseat pressure': []}

        valves = CheckValve.objects.all()

        for unit in valves:
            data['serial numbers'].append(unit.serial_number)
            data['mass'].append(unit.mass)
            data['cracking pressure'].append(unit.cracking_pressure)
            data['pressure drop'].append(unit.pressure_drop)
            data['reseat pressure'].append(unit.reseat_pressure)

        return data

Harrison方法的关键是一个映射脚本,用于将Highcharts js转换为Python模板变量:

{% extends "base.html" %}

{% block extrahead %}
    <!-- Load in jQuery and HighCharts -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="http://code.highcharts.com/highcharts.js"></script>
{% endblock %}

{% block heading %}
    <h1 align="center">Analysis</h1>
{% endblock %}

{% block content %}
    <div id={{ chartID|safe }} class="chart" style="height:100px; width:100%"></div>
{% endblock %}

{% block overwrite %}
<!-- Overwrite the base.html jQuery load and put in head for Highcharts to work -->
{% endblock %}

{% block extrajs %}
<!-- Maps the Python template context variables from views.py to the Highchart js variables -->
<script>
    var chart_id = {{ chartID|safe }}
    var chart = {{ chart|safe }}
    var title = {{ title|safe }}
    var xAxis = {{ xAxis|safe }}
    var yAxis = {{ yAxis|safe }}
    var series = {{ series|safe }}
</script>

<!-- Highchart js. Variable map shown above -->
<script>
$(document).ready(function() {
    $(chart_id).highcharts({
        chart: chart,
        title: title,
        xAxis: xAxis,
        yAxis: yAxis,
        series: series
    });
});
</script>
{% endblock %}

一切正常,现在可以正确显示!

2020-07-27