如何改正这段代码,让每一个年份对应的销售额、利润、数量累计成三条柱状图。def order_data(request): orders = Order.objects.all().values("order_date","sales","quantity","profit") data = {"order_date":[],"sales":[],"quantity":[],"profit":[]} for order in orders: if order['order_date'] != None: order_date_str = order['order_date'].strftime('%Y-%m-%d') order_date = datetime.strptime(order_date_str, '%Y-%m-%d').date() data['order_date'].append(order_date.strftime('%Y')) else: continue data['sales'].append(order['sales']) data['quantity'].append(order['quantity']) data['profit'].append((order['profit'])) return JsonResponse(data)$.get("order_data",function (data){ var year = data.order_date; var sales = data.sales; var quantity = data.quantity; var profit = data.profit; console.log(year); myChart.setOption({ xAxis: { type: 'category', data: year }, yAxis: { type: 'value' }, series: [ { name: 'sales', type: 'bar', data: sales, itemStyle: { color: 'red' } }, { name: 'quantity', type: 'bar', data: quantity, itemStyle: { color: 'yellow' } }, { name: 'profit', type: 'bar', data: profit, itemStyle: { color: 'green' } } ] });
时间: 2024-03-15 16:45:50 浏览: 46
可以将数据按年份进行分组,并分别计算每个年份的销售额、利润、数量,然后将这些数据分别作为三个系列的数据,绘制成三条柱状图。
修改后的代码如下:
```
def order_data(request):
orders = Order.objects.all().values("order_date","sales","quantity","profit")
data = {"order_date":[],"sales":[],"quantity":[],"profit":[]}
year_data = {} # 按年份分组后的数据
for order in orders:
if order['order_date'] is not None:
order_date_str = order['order_date'].strftime('%Y-%m-%d')
order_year = datetime.strptime(order_date_str, '%Y-%m-%d').date().strftime('%Y')
if order_year not in year_data:
year_data[order_year] = {"sales":0, "quantity":0, "profit":0}
year_data[order_year]["sales"] += order["sales"]
year_data[order_year]["quantity"] += order["quantity"]
year_data[order_year]["profit"] += order["profit"]
else:
continue
for year, year_sales in year_data.items():
data['order_date'].append(year)
data['sales'].append(year_sales["sales"])
data['quantity'].append(year_sales["quantity"])
data['profit'].append(year_sales["profit"])
return JsonResponse(data)
```
然后在前端代码中,将数据按照 series 的方式进行配置:
```
$.get("order_data",function (data){
var year = data.order_date;
var sales = data.sales;
var quantity = data.quantity;
var profit = data.profit;
console.log(year);
myChart.setOption({
xAxis: {
type: 'category',
data: year
},
yAxis: {
type: 'value'
},
series: [
{
name: 'sales',
type: 'bar',
data: sales,
itemStyle: {
color: 'red'
}
},
{
name: 'quantity',
type: 'bar',
data: quantity,
itemStyle: {
color: 'yellow'
}
},
{
name: 'profit',
type: 'bar',
data: profit,
itemStyle: {
color: 'green'
}
}
]
});
});
```
阅读全文