通过JSON将Django数据库查询传递给Highcharts [英] Passing Django Database Queryset to Highcharts via JSON

查看:337
本文介绍了通过JSON将Django数据库查询传递给Highcharts的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次海报,长时间的读者。我花了相当多的时间寻找一个答案,这使我觉得它的东西我失踪了。



我试图拉取数据库表中的数据,并将其传递到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导入ChartData

def chart_data_json(request):
data = {}
data ['chart_data'] = ChartData.get_data()
返回JsonResponse(数据,安全= true)

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

get_data()函数:

 #unit / analysis_funcs来自unit.models导入的.py 
CheckValve

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

valve = CheckValve.objects.all()

阀门单位:
data ['serial_numbers']。 .serial_number)
data ['mass']。append(un it.mass)

返回数据

模板:

 <! -  templates / unit / data_plot.html  - > 
{%extendsbase.html%}

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

{%block rootcontainer%}
< div id =containerstyle =width:100%; height:400px;> < / DIV>
{%endblock%}

{%block overwrite%}
<! - 覆盖base.html jQuery加载,并放在Highcharts的工作中 - > ;
{%endblock%}

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

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

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

最后的URL:

 单位导入视图,图形

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,但是经过这么长时间的盯着它,我会越过眼睛。



任何帮助都会很棒!

解决方案

我终于得到了我的绘图工作。我发现这种方法 here 。感谢 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:'止回阀数据'}
xAxis = {title:{text:'Serial Number'},categories:data ['serial numbers'] }
yAxis = {title:{text:'Data'}}
series = [
{name:'Mass(kg)',data ['mass']},
{name:'压降(psid)',data:data ['pressure drop']},
{name psid)',data:data ['crack pressure']}
]

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

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

 code> class ChartData(object):
def check_valve_data():
data = {'serial numbers':[],'mass':[],
'pressure drop' :[],'开启压力':[],'reseat pressure':[]}

valve = CheckValve.objects.all()

为阀门单位:
data ['serial numbers']。append(unit.serial_number)
data ['mass']。append(unit.mass)
data ['crack pressure']。append .cracking_pressure)
data ['pressure drop']。append(unit.pressure_drop)
data ['reseat pressure']。append(unit .reseat_pressure)

返回数据

哈里森方法的关键是映射将Highcharts js转换为Python模板变量的脚本:

  {%extendsbase.html%} 

{%block extrahead%}
<! - 加载在jQuery和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%}

{%块标题%}
< h1 align =center>分析< / h1>
{%endblock%}

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

{%block overwrite%}
<! - 覆盖base.html jQuery加载,并放在Highcharts的工作中 - > ;
{%endblock%}

{%block extrajs%}
<! - 将Python模板上下文变量从views.py映射到Highchart js变量 - > ;
< 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。上图显示的变量 - >
< script>
$(document).ready(function(){
$(chart_id).highcharts({
chart:chart,
title:title,
xAxis:xAxis ,
yAxis:yAxis,
系列:系列
});
});
< / script>
{%endblock%}

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


First time poster, long time reader. I've spend quite awhile looking for an answer to this, which makes me think its something fundamental I'm missing.

I'm trying to pull data held in a database table and pass it through for display in a Highcharts plot. I'm not getting any errors from Django or by the client when inspecting source.

Using: Django 1.7 and Python 3.4

The 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', {})

The get_data() function:

#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

The template:

<!-- 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 %}

Finally the urls:

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'),

)

Everything seems to run, but the Highchart plot doesn't render. I think its in how I'm moving the JSON data from the view.py to the template.html, but after so long staring at it I'm going cross-eyed.

Any help would be awesome!

解决方案

I finally got my plotting working. I found this approach here. Thanks to Harrison for posting his method!

My new views.py based on the above approach:

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})

Quick function for pulling database objects and passing the data:

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   

The key to Harrison's method is a mapping script to translate the Highcharts js to Python template variables:

{% 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 %}

Everything works and displays correctly now!

这篇关于通过JSON将Django数据库查询传递给Highcharts的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆