python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Django 图表数据交互

Django与图表的数据交互的实现

作者:菜鸡一枚____

本文主要介绍了Django与图表的数据交互的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

在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数据

到此这篇关于Django与图表的数据交互的实现的文章就介绍到这了,更多相关Django 图表数据交互内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文