有没有一种方法可以轻松地将JSON对象传递给Chart.js的Django上下文?

时间:2018-07-27 12:22:33

标签: python django chart.js

我想使用Chart.js作为绘图工具,并编写一个Django视图,该视图将运行ORM查询,获取一些数据,将其转换为JSON,将JSON数据传递给Django上下文,并在Django模板没有太多麻烦。我希望这样做尽可能简单。

我可以用Highcharts-django来做这样的事情,但是价格太高了。

这大致就是我想做的:

(1)通过views.py中的ORM查询获取加载到“ get_context_data”中的数据,并使用“ {_1}}方法generate_chart(data)

将数据格式化为json
from local_utils import generate_chart

class MyView(TemplateView):
    template_name = "template.html"

    def get_context_data(self, *args, **kwargs):
        data_source = MyModel.objects.fitler(start_date__gte=start_date).values()
        my_chart = generate_chart(data_source)
        context['my_chart'] = my_chart

(2)将数据传递到方法generate_chart(data_source)并返回LineChartJSONView对象(或其他对象)

from random import randint
from django.views.generic import TemplateView
from chartjs.views.lines import BaseLineChartView

def generate_chart(data_source):
    class LineChartJSONView(BaseLineChartView):
        def get_labels(self):
            """Return labels for the x-axis."""
            return data_source.values_list('x-data', flat=True)

        def get_providers(self):
            """Return names of datasets."""
            return ['data']

        def get_data(self):
            """Return datasets to plot on y-axis."""
            return data_source.values_list('y-data', flat=True)

    line_chart = TemplateView.as_view(template_name='line_chart.html')
    line_chart_json = LineChartJSONView.as_view()

    return line_chart_json

(3)将上下文对象my_chart传递给template.html

<head>
    {{ my_chart|load_data_to:"container" }}
</head>
<body>
    {# Other stuff #}
    {% if chart %}
        <div id='container'>Chart will go here</div>
    {% endif %}
    {# Other stuff #}
</body>

(4)绘制以下内容:https://github.com/peopledoc/django-chartjs#3-get-a-chartjs-line-chart

我见过the usage in the docs,其中视图中唯一发生的事情是绘图。但是,我想将绘图嵌入到TemplateView中。 Chart.js有可能吗?如果是,怎么办?

0 个答案:

没有答案