Pyhon:异常值:“str”和“int”的操作数类型不受支持

2024-07-02 10:42:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我在django项目中设置了以下类:

型号.py

class Budget_Vendite(models.Model):
    MY_CHOICES = (
        ('jan', 'jan'),
        ('feb', 'feb'),
        ('mar', 'mar'),
        ('apr', 'apr'),
    )
    month = models.CharField(max_length=10, choices=MY_CHOICES, default="")
    year=models.IntegerField(default="")
    prodotto=models.ForeignKey()
    sottoprodotto=models.ForeignKey()
    prezzo_unitario=models.DecimalField()
    quantita=models.DecimalField() 

在我看来,我设置了以下代码:

视图.py

defaults = list(0 for m in range(12))
for prodotto_id, year, month, totale in(Budget_Vendite.objects.values_list('prodotto__name', 'year', 'month').annotate(totale=ExpressionWrapper(Sum(F('quantita') * F('prezzo_unitario')),
        output_field=FloatField())).values_list('prodotto__name', 'year', 'month', 'totale')):
        if prodotto_id not in ricavi_bdgt_2.keys():
            ricavi_bdgt_2[prodotto_id]=list(defaults)
        index=month-1
        ricavi_bdgt_2[prodotto_id][index]=totale

    total_ricavi_2={'Fatturato Previsionale': [sum(t) for t in zip(*ricavi_bdgt_2.values())]}

但django告诉我以下错误:

 File "C:\Users\Federico\Desktop\Prova test\Budgeting\budget_vendite\func.py", line 36, in ce_func_bdgt

index=month-1
TypeError: unsupported operand type(s) for -: 'str' and 'int'

错误在哪里


Tags: djangoinpyidforindexmodelsyear
1条回答
网友
1楼 · 发布于 2024-07-02 10:42:23

语句index=month-1是导致此错误的原因。变量month是string类型,因此必须将其转换为整数或其他数字类型,然后才能对其进行算术运算

在您的代码段中,需要获取MY_CHOICES列表中month值的索引

index=MY_CHOICES.index(month)

这将解决问题

相关问题 更多 >