我有两个模型。一个是具有branch_id和branch_name字段的Branch,另一个是具有sales_amount和year字段的Sales。分支机构和销售部门具有ForeignKey关系。一个分支可以有多个销售。我要实现的目标是按照每年具有销售价值的年份分组。并获取键(分支名称)和值(sales_list)的字典。如果该年没有销售,则值应为“ 0”。
models.py
import datetime
from django.db import models
class Branch(models.Model):
branch_id = models.IntegerField()
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Sales(models.Model):
branch = models.ForeignKey('Branch', on_delete = models.CASCADE)
sales_amount = models.IntegerField()
year = models.CharField(max_length=4)
class Meta:
unique_together = (('year', 'branch'),)
def __str__(self):
return self.branch.name
views.py
from django.shortcuts import render
import json
from .models import Branch, Sales
def index(request):
branches = Branch.objects.all()
sales = Sales.objects.all()
sales_list = []
branch_list = []
year_set = set()
for sale in sales:
year_set.add(sale.year)
year_list = list(sorted(year_set))
for branch in branches:
sales_list.append(branch.sales_set.all().order_by('year'))
branch_list.append(branch.name)
sales_list = [[j.sales_amount for j in i] for i in sales_list]
branch_dict = dict(zip(branch_list, sales_list))
return render(request, 'index.html', {
'year_list': year_list,
'branch_dict': branch_dict
})
我
BRANCH001 with the year 2011 has 5000 sales, BRANCH001 with the year 2012 has 10000 sales
,
BRANCH002 with the year 2011 has 7000 sales
expected output = {'BRANCH001': [5000, 10000], 'BRANCH002': [0, 7000]}
actual output = {'BRANCH001': [5000, 10000], 'BRANCH002': [7000]}