django - Django,`KeyError` 在表格中
问题描述
我创建了一个应用程序,让我可以收集和存储所有日常收入。在这种情况下,我创建了以下模型:
class Income(models.Model):
income=models.DecimalField()
date=models.DateField()
在我看来,我创建了一个算法,可以让我每月收集所有日期,如下所示:
now=datetime.datetime.now()
now=now.year
income=dict()
for year, month, totals in(Income.objects.values_list( 'date__year', 'date__month').
annotate(totals=ExpressionWrapper(Sum(F('income')),
output_field=FloatField())).values_list('date__year', 'date__month', 'totals')):
if id not in income.keys() and year == now:
income[id]=list(defaults)
index=month-1
income[id][index]=totals
一切都完美无缺。但现在我想给出能够选择年份管理now
变量的可能性。因此,为了这个目标,我尝试创建一个新模型,如下所示:
class Timing(models.Model):
TYPE=[
('2020','2020'),
('2021', '2021'),
]
reference_year=models.CharField('Azienda/Privato', max_length=30, choices=TYPE, default="")
在我看来,我添加了代码:
now='2020'
if request.method == 'POST':
form = TimingForm(request.POST)
if form.is_valid():
now = form.cleaned_data['reference_year']
但是 django 给了我KeyError <built-in function id>
. 问题出在哪里?我认为问题在于 now 不是日期时间变量?
解决方案
我认为if id not in income.keys() and year == now:
id 存在问题 - 它是内置函数,您需要使用字符串 'id'。也改变这一行income[id]=list(defaults)
。
推荐阅读
- android - android app beta版和公版可以存在于同一部手机吗?
- javascript - 如何在多个页面中包含搜索或过滤功能
- mongodb - 如何修复 mongodb spring boot 应用程序中 LocalDate 字段的 localdate UTC 问题?
- node.js - 如何扩展这个用户界面?
- telegram - 如何在电报中获取可用于 TdApi 中的 t.me URL 的消息 ID?
- flutter - 无法将firebase存储图像网址存储到firestore
- python - 错误:由于环境错误而无法安装软件包:[Errno 9] 文件描述符错误
- r - 警告:terms.formula 中的错误:找不到对象“risktable”
- google-analytics - 如何在 Google Analytics 中获取完整的引荐来源网址(社交网络)
- javascript - JQuery datepicker 未通过在我的 asp.Net 核心应用程序中发布来发送选定的值