在Django开发过程中,遇到了需要图表进行数据可视化的需要。因此查询了相关文档,并记录下如何实现与图表的数据交互。 本人是个前端小白,只会改不会写(套模板)。
仅供参考!!!
Django (版本不限,当然不同的版本有不同的后端代码写法。本文环境为Django 3.1)
echarts (前端的画图框架,导入JS包即可) 点击网址可以找到模板 网址
JQuery (用于Ajax请求 导入JS包即可 在文中会有JS包地址)
urls.py
re_path('ajax_line/', views.ajax_line, name='ajax_line'),
ajax请求接口:
def ajax_line(request):
# 数据处理
# 要求: 统计前5个月的销售额
DateSum = []
Date = []
# 取前5个月的日期
for i in range(0,5):
month = datetime.date(datetime.date.today().year, datetime.date.today().month - i, 1) # 当月一号
Date.append(month)
# 分别取30天的销售额
ShopList = ShopOrders.objects.filter( add_time__year=month.year, add_time__month=month.month)
sum = 0
for j in ShopList :
sum += j.Money
DateSum.append(sum)
# 数据打包
jsondata = {
"Date": Date,
"DateSum": DateSum
}
cities = []
for n, c in zip(jsondata['Date'], jsondata['DateSum']):
b = {}
b['name'] = n
b['count'] = c
cities.append(b)
test_dic = {}
test_dic['data'] = cities
# 将数据转换成json格式,方便ajax调用
return JsonResponse(test_dic, safe=False)
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
前端
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>