Django查询数据库并将数据发送到模板

时间:2017-02-06 07:40:14

标签: django postgresql django-models highcharts django-views

我还是Django / web开发的新手,但有Python和PSQL的经验。

我有一个psql数据库,其中包含一个对于股票投资组合具有 id,date和value 的表。该表的标题是absolutedollarvalue。

我想将数据发送到模板,然后使用Highcharts.JS对其进行绘图。根据我的理解,我需要设置models.py来查询数据库,该数据库安装在Django中,将其转换为JSON,然后将其发送到模板进行绘图。

有人能告诉我这是否是获取id,date和value的正确语法,以及如何以json格式将日期和值发送到模板?

这是适用的模型部分:

class Absolutedollarvalue(models.Model):
    cik = models.CharField(max_length=16)
    date = models.DateField()
    value = models.DecimalField(max_digits=65535, decimal_places=65535)

    class Meta:
        managed = False
        db_table = 'absolutedollarvalue'

以下是我的views.py代码:

from django.shortcuts import render
from django.http import HttpResponse
from django.db import connection
from toa.models import Absolutedollarvalue as adv
import psycopg2
import json
import datetime

def adv(request):
    adv.objects
    a = adv(id = '1103804')

    return render(request,toa/graphs.html,a)

这是我的模板:

<html>
<head>
  <title> Fund Performance </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>

</head>
<body>
  <div id="chart_container" style="width:100%; height:400px;"></div>
  <script type="text/javascript">
    $(document).ready(function() {
      var absolutedollarval = {
        chart: {
          renderTo: 'chart_panel',
          type: 'time-series',
        },
        legend: {enabled: false},
        title: {text: 'Daily NAV'},
        xAxis: {title:{text:'Date'}},
        yAxis: {title: {text: 'dollar value'}}
      };
      var chartDataUrl = "{% url 'chart_data_json' %}?name = avg_by_day"
        +"&days=14";
      $.getJSON(chartDataUrl,
      function(data){
        absolutedollarval.xAxis.categories=
        absolutedollarval.series[0].name = 
        absolutedollarval.series[0].data = 
        var chart = new Highcharts.Chart(absolutedollarval);
      });
    });
  </script>
</body>
</html>

非常感谢您提供的任何帮助。谢谢!

编辑:

如果我想要日期和值列,那么你是如何将值推送到模板的?

def adv(request): 
    dates = adv.objects.filter(cik = '1103804').values('date') 
    vals = adv.objects.filter(cik ='1103804').value('absolutedollarvalue') 
    data = serializers.serialize('json', dates) 
    data2 = serializers.serialize('json',vals) 
    return render(request,'toa/graphs.html',{"dates":data,"values":data2})

1 个答案:

答案 0 :(得分:2)

以JSON格式发送值到模板:

from django.core import serializers

def adv(request):
    adv.objects
    a = adv(id = '1103804') #Will fetch all the column
    a = adv(id = '1103804').values('columnName') #Will fetch the particular column.
    data = serializers.serialize('json', a)
    context = Context(data)
    return render(request,'toa/graphs.html',context)
    render(request, "foo.html", {'jsonKey': jsonValue}) #For passing individual JSON