Python Pyhon:异常值:';str';和';int';

Python Pyhon:异常值:';str';和';int';,python,django,django-models,django-forms,django-views,Python,Django,Django Models,Django Forms,Django Views,我在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, defa

我在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() 
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())]}
在我看来,我设置了以下代码:

视图.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() 
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'

错误在哪里?

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

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

index=MY_CHOICES.index(月)
这将解决问题