from django.db.models import Sum
for obj in User.objects.all():
print(Post.objects.filter(user=obj).aggregate(Sum('expense')))
for obj in User.objects.all():
print(obj.post_set.aggregate(Sum('expense')))
qs = User.objects.annotate(Sum('post__expense')).order_by('pk')
for obj in qs:
print(obj.post__expense__sum)
from django.db.models import Sum
for obj in User.objects.all(): # ↓ Here
print(Post.objects.filter(user=obj).aggregate(expenseSum=Sum('expense')))
for obj in User.objects.all(): # ↓ Here
print(obj.post_set.aggregate(expenseSum=Sum('expense')))
# ↓ Here
qs = User.objects.annotate(expenseSum=Sum('post__expense')).order_by('pk')
for obj in qs: # ↓ Here
print(obj.expenseSum)
3条答案
按热度按时间xzabzqsa1#
您可以执行类似以下操作来获取当前用户费用
Post.objects.filter(author=request.user).aggregate(sum = Sum('expense'))
这将返回当前登录用户的总和。9jyewag02#
您可以使用以下命令注解每个用户的总和:
由此
QuerySet
产生的User
对象将包含相关post
的expense
之和。对于已登录的用户,可以使用以下公式计算:
az31mfrm3#
您可以将aggregate()和annotate()与Sum()一起使用,按用户对
Post
模型中的expense列求和,如下所示。* 您需要将order_by('pk')
与annotate()
一起使用,否则将按降序打印值:并且,您可以将expense列的默认键
expense__sum
和post__expense
更改为expenseSum
,如下所示: