1. 程式人生 > >python專案篇-對符合條件的某個欄位進行求和,聚合函式annotate(),aggregate()函式

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

第二種輸出的是正確的數字