如何在Django中使用mysql数据库数据导入FusionCharts

问题描述 投票:0回答:1

我想通过运行查询来使用存储在 MySQL 数据库中的数据,并在 FusionCharts 的帮助下显示数据。

现在 fusionCharts 使用 json 数据格式,但 MySQL 数据不使用。

如何使用 fusionCharts 显示我的数据库数据。我需要代码方面的帮助。

这是我的views.py(这不是所有的views.py,只是相关的一个。)

from .fusioncharts import FusionCharts
def chart(request):
    # Create an object for the column2d chart using the FusionCharts class constructor
  monthly = FusionCharts('column2d', 'ex1', '600', '400', 'chart-1', 'json', """{
      "chart": {
        "caption": "Monthly offense",
        "subcaption": "Month of July",
        "xaxisname": "Country",
        "yaxisname": "Offenses",
        "numbersuffix": "",
        "theme": "fusion"
      },
      "data": [
        {
          "label": "Jan",
          "value": "290"
        },
        {
          "label": "Feb",
          "value": "260"
        },
        {
          "label": "Mar",
          "value": "180"
        },
        {
          "label": "April",
          "value": "140"
        },
        {
          "label": "May",
          "value": "115"
        },
        {
          "label": "June",
          "value": "100"
        },
        {
          "label": "July",
          "value": "30"
        },
        {
          "label": "Aug",
          "value": "30"
        },
        {
          "label": "Sept",
          "value": "30"
        },
        {
          "label": "Oct",
          "value": "30"
        },
        {
          "label": "Nov",
          "value": "30"
        },
        {
          "label": "Dec",
          "value": "30"
        }
      ]
  }""")

  context = {
        'all_count': all_count,
        'total_high': total_high,
        'total_medium': total_medium,
        'total_low': total_low,
        'monthly': monthly.render(),
        'status': status.render(),
        'category_chart': category_chart.render(),
        'all_category': all_category.render()
  }

    # returning complete JavaScript and HTML code, which is used to generate chart in the browsers.
  return  render(request, 'dashboard.html', {'context': context})

到目前为止我已经尝试过了。我制作了一个字典,然后将其转换为 json 并将其传递给我的图表对象。它在 html 模板上给出了“无效数据”。

all_count = Offenses.objects.all().count()
    open_status = Offenses.objects.filter(status__iexact='OPEN').count()
    closed_status = Offenses.objects.filter(status__iexact='CLOSED').count()
    hidden_status = Offenses.objects.filter(status__iexact='HIDDEN').count()
    high1 = Offenses.objects.filter(magnitude=7).count()
    high2 = Offenses.objects.filter(magnitude=6).count()
    high3 = Offenses.objects.filter(magnitude=8).count()
    high4 = Offenses.objects.filter(magnitude=9).count()
    medium1 = Offenses.objects.filter(magnitude=5).count()
    medium2 = Offenses.objects.filter(magnitude=4).count()
    medium3 = Offenses.objects.filter(magnitude=3).count()
    low1 = Offenses.objects.filter(magnitude=1).count()
    low2 = Offenses.objects.filter(magnitude=2).count()
    total_high = high1+high2+high3+high4
    total_medium = medium1+medium2+medium3
    total_low = low1+low2

    status_data = {
        'open_status': open_status,
        'closed_status': closed_status,
        'hidden_status': hidden_status,
    }
    status_data_json = json.dumps(status_data)

    status = FusionCharts('doughnut2d', 'ex3', '600', '400', 'chart-2', 'status_data_json', """{
      "chart": {
        "caption": "Offense Status",
        "showpercentvalues": "1",
        "aligncaptionwithcanvas": "0",
        "captionpadding": "0",
        "decimals": "1",
        "plottooltext": "<b>$percentValue</b> of offenses are <b>$label</b>",
        "centerlabel": "# Users: $value",
        "theme": "fusion"
      },
      "data": [
        {
          "label": "Opened offense",
          "value": "open_status"
        },
        {
          "label": "Closed offense",
          "value": "5300"
        }
      ]
    }""")
python django python-3.x fusioncharts
1个回答
0
投票

除了直接在 JSON/XML 代码中指定图表数据(或存储图表数据的文件的 URL)之外,您还可以从数据库中获取图表数据。

Django 模型(大致)映射到数据库表 -

from django.db import models

class Revenue(models.Model):
    MonthlyRevenue = models.CharField(max_length=50)
    Month = models.CharField(max_length=50)

    def __unicode__(self):
        return u'%s %s' % (self.MonthlyRevenue, self.Month)

示例代码-

from django.shortcuts import render
from django.http import HttpResponse

# Include the `fusioncharts.py` file that contains functions to embed the charts.
from fusioncharts import FusionCharts

from ..models import *

# The `chart` function is defined to generate Column 2D chart from database.
def chart(request):
    # Chart data is passed to the `dataSource` parameter, as dict, in the form of key-value pairs.
    dataSource = {}
    dataSource['chart'] = {
        "caption": "Monthly revenue for last year",
            "subCaption": "Harry's SuperMart",
            "xAxisName": "Month",
            "yAxisName": "Revenues (In USD)",
            "numberPrefix": "$",
            "theme": "zune"
        }

    # The data for the chart should be in an array where each element of the array is a JSON object
    # having the `label` and `value` as key value pair.

    dataSource['data'] = []
    # Iterate through the data in `Revenue` model and insert in to the `dataSource['data']` list.
    for key in Revenue.objects.all():
      data = {}
      data['label'] = key.Month
      data['value'] = key.MonthlyRevenue
      dataSource['data'].append(data)

    # Create an object for the Column 2D chart using the FusionCharts class constructor
    column2D = FusionCharts("column2D", "ex1" , "600", "350", "chart-1", "json", dataSource)
    return render(request, 'index.html', {'output': column2D.render()})

要了解有关此功能的更多信息,请参阅 - https://www.fusioncharts.com/dev/getting-started/django/create-charts-in-django-using-database

希望这对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.