改正这段代码,读出的数据不对,且只有2018年的错误数据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'] != 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""" 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"] """data['sales'].append(order['sales']) data['quantity'].append(order['quantity']) data['profit'].append((order['profit'])) return JsonResponse(data)""" 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)
时间: 2024-04-20 13:27:24 浏览: 79
def order_data(request):
orders = Order.objects.filter(order_date__year=2018).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_year = order['order_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"]
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)
这个函数做的事情是读取 Order 模型中 2018 年的订单数据,并且将数据按年份分组,计算每年的销售额、销售数量和利润,并返回一个 JSON 格式的数据。我将函数修改了一下,使它只读取 2018 年的数据,并且去掉了一些不必要的代码。
阅读全文