亲宝软件园·资讯

展开

Django 图表数据交互

菜鸡一枚____ 人气:0

在Django开发过程中,遇到了需要图表进行数据可视化的需要。因此查询了相关文档,并记录下如何实现与图表的数据交互。 本人是个前端小白,只会改不会写(套模板)。
仅供参考!!!

环境相关

Django (版本不限,当然不同的版本有不同的后端代码写法。本文环境为Django 3.1)
echarts (前端的画图框架,导入JS包即可) 点击网址可以找到模板 网址
JQuery (用于Ajax请求 导入JS包即可 在文中会有JS包地址)

实现思路(需要理解的请结合代码来看)

代码:

urls.py

re_path('ajax_line/', views.ajax_line, name='ajax_line'),

ajax请求接口:

  from django.db import models
from datetime import datetime
# Create your models here.

class Shop(models.Model):
    Name = models.CharField(max_length=50, verbose_name='名称')
    Barcode = models.CharField(max_length=50, verbose_name='条形码' ,default ='')
    Money = models.IntegerField(default=0, verbose_name='单价')
    number = models.IntegerField(default=0, verbose_name='库存')
    Other = models.CharField(max_length=100, verbose_name='备注' ,default='无')
    objects = models.Manager()
    def __str__(self):
        return self.Name
    class Meta:
        verbose_name = '商品'
        verbose_name_plural = verbose_name

class ShopOrders(models.Model):
    Produce = models.ManyToManyField(Shop, verbose_name='产品清单', blank=True)
    Money = models.IntegerField(default=0, verbose_name='合计')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='时间')
    Other = models.CharField(max_length=100, verbose_name='备注' , default='无')
    Owner =  models.CharField(max_length=50, verbose_name='销售人员',default ='')
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    YEAR_IN_SCHOOL_CHOICES = (
        (FRESHMAN, '微信'),
        (SOPHOMORE, '现金'),
        (JUNIOR, '支付宝'),
    )
    Type = models.CharField(
        max_length=2,
        choices=YEAR_IN_SCHOOL_CHOICES,
        default=FRESHMAN,
    )

    objects = models.Manager()
    def __str__(self):
        return self.Owner
    class Meta:
        verbose_name = '商品订单'
        verbose_name_plural = verbose_name

models

  from django.db import models
from datetime import datetime
# Create your models here.

class Shop(models.Model):
    Name = models.CharField(max_length=50, verbose_name='名称')
    Barcode = models.CharField(max_length=50, verbose_name='条形码' ,default ='')
    Money = models.IntegerField(default=0, verbose_name='单价')
    number = models.IntegerField(default=0, verbose_name='库存')
    Other = models.CharField(max_length=100, verbose_name='备注' ,default='无')
    objects = models.Manager()
    def __str__(self):
        return self.Name
    class Meta:
        verbose_name = '商品'
        verbose_name_plural = verbose_name

class ShopOrders(models.Model):
    Produce = models.ManyToManyField(Shop, verbose_name='产品清单', blank=True)
    Money = models.IntegerField(default=0, verbose_name='合计')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='时间')
    Other = models.CharField(max_length=100, verbose_name='备注' , default='无')
    Owner =  models.CharField(max_length=50, verbose_name='销售人员',default ='')
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    YEAR_IN_SCHOOL_CHOICES = (
        (FRESHMAN, '微信'),
        (SOPHOMORE, '现金'),
        (JUNIOR, '支付宝'),
    )
    Type = models.CharField(
        max_length=2,
        choices=YEAR_IN_SCHOOL_CHOICES,
        default=FRESHMAN,
    )

    objects = models.Manager()
    def __str__(self):
        return self.Owner
    class Meta:
        verbose_name = '商品订单'
        verbose_name_plural = verbose_name

前端

<!--
   THIS EXAMPLE WAS DOWNLOADED FROM https://echarts.apache.org/examples/zh/editor.html?c=line-simple
-->
<!DOCTYPE html>
<html lang="zh-CN" style="height: 100%">
<head>
  <meta charset="utf-8">
</head>
<body style="height: 100%; margin: 0">

<h1 style="Text-align:center"> 月度销售情况</h1>>
  <div id="container" style="height: 100%"></div>


 <script type="text/javascript" src="https://fastly.jsdelivr.net/npm/echarts@5.3.3/dist/echarts.min.js"></script>
 <script type="text/javascript" charset="utf8" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

  <script type="text/javascript">
    var dom = document.getElementById('container');
    var myChart = echarts.init(dom, null, {
      renderer: 'canvas',
      useDirtyRect: false
    });
    var app = {};
    
    var option;

    option = {
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [],
      type: 'line'
    }
  ]
};

    if (option && typeof option === 'object') {
      myChart.setOption(option);
    }
    window.addEventListener('resize', myChart.resize);

    myChart.showLoading();
    var names = [];
    var brower = [];
    $.ajax({ // ajax的方式动态获取后端代码
        type: 'get',
        url: '/index/ajax_line/',
        dataType: 'json',
        success: function (result) {
                $.each(result.data, function (index, item) {
                names.push(item.name);
                brower.push({
                    value: item.count,
                    name: item.name
                });
            });
            myChart.hideLoading();
            myChart.setOption({
                xAxis: {
                    data: names
                },
                series: [{
                    data: brower
                }]
            });
        },
        error: function (errormsg) {
            alert('errormsg');
            myChart.hideLoading();
        }
    });

  </script>

</body>
</html>

成果展示

在这里插入图片描述

参考博客

echarts动态获取Django数据

加载全部内容

相关教程
猜你喜欢
用户评论