我需要找到具有最大fat_intake (整体fat_intake)的user_id。
数据库:
id | user_id | fat_intake
38 1 10
39 1 15
40 1 30
41 1 14
42 2 20
43 2 30
44 2 50 获得最大脂肪摄入量的user_id的查询是什么?
响应应该是:
Output:
{
"user_id": 1,
"total_fat_count": 69
} 我试过了:
maxCalorie = CalorieInfo.objects.annotate(fat_intake=Avg('fat_intake')).aggregate(Max('fat_intake'))发布于 2020-03-17 15:27:29
你可以这样做,
In [27]: from django.db.models import Sum
In [28]: CalorieInfo.objects.all().values('user_id').annotate(fat_intake=Sum("fat_intake"))
Out[28]: <QuerySet [{'user_id': 1, 'fat_intake': 69}]>
In [29]:发布于 2020-03-17 15:58:08
这是正确的答案,它应该适用于您。
users.objects.values('user_id').annotate(total=Sum('fat_intake'))输出为
<QuerySet [{'user_id': 1, 'total': 69}, {'user_id': 2, 'total': 100}]>https://stackoverflow.com/questions/60717817
复制相似问题