如何通过外键分组进行查询,并按字段求和排序

时间:2016-03-03 18:09:53

标签: django django-queryset

例如我有一个模型:

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字段排序。我该怎么做这样的查询?

1 个答案:

答案 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')