我需要找到具有最大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'))
答案 0 :(得分:1)
您可以这样做
[INFO] Building fake_id 1.0.0
[INFO] ------------------------------------------------------------------------
Downloading: https://repo.maven.apache.org/maven2/javax/inject/javax.inject/1/javax.inject-1.pom
Downloaded: https://repo.maven.apache.org/maven2/javax/inject/javax.inject/1/javax.inject-1.pom (612 B at 0.5 KB/sec)
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ fake_id ---
[INFO] fake_id:fake_id:jar:1.0.0
[INFO] \- org.glassfish.jersey.containers:jersey-container-servlet:jar:2.19:compile
[INFO] +- org.glassfish.jersey.containers:jersey-container-servlet-core:jar:2.19:compile
[INFO] | \- org.glassfish.hk2.external:javax.inject:jar:2.4.0-b25:compile
[INFO] +- org.glassfish.jersey.core:jersey-common:jar:2.19:compile
[INFO] | +- javax.annotation:javax.annotation-api:jar:1.2:compile
[INFO] | +- org.glassfish.jersey.bundles.repackaged:jersey-guava:jar:2.19:compile
[INFO] | +- org.glassfish.hk2:hk2-api:jar:2.4.0-b25:compile
[INFO] | | +- org.glassfish.hk2:hk2-utils:jar:2.4.0-b25:compile
[INFO] | | \- org.glassfish.hk2.external:aopalliance-repackaged:jar:2.4.0-b25:compile
[INFO] | +- org.glassfish.hk2:hk2-locator:jar:2.4.0-b25:compile
[INFO] | | \- org.javassist:javassist:jar:3.18.1-GA:compile
[INFO] | \- org.glassfish.hk2:osgi-resource-locator:jar:1.0.1:compile
[INFO] +- org.glassfish.jersey.core:jersey-server:jar:2.19:compile
[INFO] | +- org.glassfish.jersey.core:jersey-client:jar:2.19:compile
[INFO] | +- org.glassfish.jersey.media:jersey-media-jaxb:jar:2.19:compile
[INFO] | \- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] \- javax.ws.rs:javax.ws.rs-api:jar:2.0.1:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
答案 1 :(得分:0)
这是正确的答案,应该对您有用。
users.objects.values('user_id').annotate(total=Sum('fat_intake'))
输出为
<QuerySet [{'user_id': 1, 'total': 69}, {'user_id': 2, 'total': 100}]>