For example I have a model:
class Reward(models.Model):
user = models.ForeignKey(UserProfile)
amount = models.IntegerField()
I want to get such statistics:
[{
"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,
...
}
]
This list should be ordered by total_amount
field. How should I do such query?
You can do that with 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')
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments