【问题标题】:Django: unsupported operand type(s) for +: 'int' and 'str'Django:+:'int'和'str'不支持的操作数类型
【发布时间】:2021-09-19 08:53:37
【问题描述】:

我想使用 aggregate(sum()) 函数对模型的所有字段求和,但出现此错误。

Views.py

def paymentdailyreport(request):
    cashsum= Payment.objects.filter(PaymentMethod="Cash").aggregate(sum('Amount'))
    print(cashsum)
    context={

    }
    return render(request,'paymentdailyreport.html',context)

Models.py

 class Payment(models.Model):
        Date=models.CharField(max_length=20)
        User=models.CharField(max_length=50)
        PatientName=models.CharField(max_length=50)
        Dentist=models.CharField(max_length=50)
        Scheme=models.CharField(max_length=50)
        PaymentMethod=models.CharField(max_length=50)
        Amount=models.DecimalField(max_digits=20,decimal_places=3)
        def __str__(self):
            return self.Date + " | " + self.User + " | " + self.PatientName

【问题讨论】:

    标签: django django-models django-views


    【解决方案1】:

    您不能使用内置的sum 对值求和:您指定用Sum expression [Django-doc] 确定总和:

    from django.db.models import Sum
    
    def paymentdailyreport(request):
        #                                         use Sum instead of sum ↓
        cashsum= Payment.objects.filter(PaymentMethod="Cash").aggregate(Sum('Amount'))
        print(cashsum)
        context={
            'cashsum': cashsum
        }
        return render(request,'paymentdailyreport.html',context)

    【讨论】:

    • 它说“名称总和未定义”
    • @ZPro:你需要导入它,就像代码片段顶部写的那样......
    • 好的,我明白了
    猜你喜欢
    • 2022-07-27
    • 2016-04-15
    • 2012-11-29
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 2021-11-16
    相关资源
    最近更新 更多