python项目篇-对符合条件的某个字段进行求和,聚合函数annotate(),aggregate()函数

对符合条件的某个字段求和
需求是,计算每日的收入和
1、

 new_dayincome = request.POST.get("dayincome_time", None)

        # total_income = models.bathAccount.objects.filter(dayBath=new_dayincome).aggregate(nums=Sum('priceBath'))
        total_income =  models.bathAccount.objects.values('priceBath').annotate(nums=Sum('priceBath')).filter(dayBath=new_dayincome)
        print("total_income",total_income[0]['nums'])
 
输出结果:total_income 132

2、

		from django.db.models import Sum,Count
		new_dayincome = request.POST.get("dayincome_time", None)

        total_income = models.bathAccount.objects.filter(dayBath=new_dayincome).aggregate(nums=Sum('priceBath'))
        print("total_income",total_income['nums'])
  输出结果:total_income  572

第二种输出的是正确的数字

你可能感兴趣的:(Python,Django,项目,Python面试笔记)