例如我有一个模型:
class Reward(models.Model):
user = models.ForeignKey(UserProfile)
amount = models.IntegerField()
我想得到这样的统计数据:
[{
"user": user1,
"total_amount": 100500, // Sum of amount field of all rewards for this user
"total_rewards": 13 // Count of rewards for this user
},
{
"user": user2,
...
}
]
此列表应按total_amount
字段排序。我该怎么做这样的查询?
答案 0 :(得分:1)
您可以使用annotate
from django.db.models import Count, Sum
UserProfile.objects.annotate(
total_amount=Sum('reward__amount'),
total_rewards=Count('reward')
).values('id', 'total_amount', 'total_rewards').order_by('total_amount')