从数据库获取数据以Json格式返回前端数据可视化方式显示,效果如下
1. 在view.py文件中,将json对象需要做处理
import json
def echart(request):
json_list = []
for i in ret:
json_dict = {}
json_dict["id"] = i.id
json_dict["totalIncome"] = i.totalIncome
json_dict["dayIncome"] = i.dayIncome
json_dict["remarkIncome"] = i.remarkIncome
json_dict["totalBath"] = i.totalBath
json_dict["totalBathHouse"] = i.totalBathHouse
json_dict["totalHouse"] = i.totalHouse
json_dict["totalPay"] = i.totalPay
json_list.append(json_dict)
return render(request,'echart.html',{"ret": json.dumps(ret1)})
2. 前端接口来着django后端传过来的json,需要再做处理
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('echart'));
var ret={{ ret|safe }};
var obj =JSON.parse(ret)
var jsdayIncome = []
var jstotallIncome = []
console.log(obj);
for(i in obj){
jsdayIncome.push(obj[i]['dayIncome'])
}
for(i in obj){
jstotallIncome.push(obj[i]['totalIncome'])
}
console.log(jsdayIncome)
console.log(jstotallIncome)
// 指定图表的配置项和数据
var option = {
title: {
text: '每日收入可视化'
},
tooltip: {},
legend: {
data:['收入']
},
xAxis: {
data: jsdayIncome
},
yAxis: {},
series: [{
name: '收入',
type: 'bar',
data: jstotallIncome
}]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>