Django aggregate sum for each user

Viewed 473

I'm creating a budget application and wanted to find the sum of each user who's signed in. Right now I'm using function-based views and I sum up the expenses with Post.objects.aggregate(sum = Sum('expense')) The issue with this is it sums up everyone in the database but I wanted it to only sum up the expenses of the user that is currently signed in. In my model, I have an author field but I'm not sure how to go about summing only for the user currently signed in.

2 Answers

You can do something like this to get current user expense

Post.objects.filter(author=request.user).aggregate(sum = Sum('expense')) this will return sum of current logged In user.

You can annotate the sum for each user, with:

from django.db.models import Sum

User.objects.annotate(total=Sum('post__expense'))

The User objects that arises from this QuerySet will contain the sum of the expenses of the related posts.

For the logged in user, you can calculate this with:

from django.db.models import Sum

request.user.post_set.aggregate(total=Sum('expense'))['total'] or 0
Related