` 在表格中,django,django-models,django-forms,django-views,django-templates"/>

首页 > 解决方案 > 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 不是日期时间变量?

标签: djangodjango-modelsdjango-formsdjango-viewsdjango-templates

解决方案


我认为if id not in income.keys() and year == now: id 存在问题 - 它是内置函数,您需要使用字符串 'id'。也改变这一行income[id]=list(defaults)


推荐阅读