0

My code, models.py

class accounts(models.Model):
    paid = models.DecimalField(max_digits=8, decimal_places=2, default=0)
    balance = models.DecimalField(max_digits=8, decimal_places=2, default=0)

Views.py

def home(request):
    template = "index.html"
    total_paid = Accounts.aggregate(Sum('paid'))
    total_balance = Accounts.aggregate(Sum('balance'))
    return render_to_response(template, context_instance=RequestContext(request,locals()))

And index.html

 {{ total_balance }}
 {{ total_paid }}

I want to render the amount of this fields on all users , so i use "Sum" , and i want to render it , but when i do it doesnt render the raw value , for some reason i cant undestand they return {'balance__sum': Decimal('0.00')} , i suppose its "Sum's" fault i guess

4

1 回答 1

0

聚合返回此处定义的字典https://docs.djangoproject.com/en/dev/topics/db/aggregation/。因此,如果要渲染,可以执行以下操作

def home(request):
    template = "index.html"
    total_paid = Accounts.objects.all()aggregate(Sum('paid'))
    total_balance = Accounts.objects.all()aggregate(Sum('balance'))

    context ('total_paid': total_paid['paid_sum'],
             'total_balance': total_balance['balance_sum'])
    return  render(request, template, context)

关键是您需要以某种方式将聚合函数返回的键提取到上下文中,然后在模板中使用它

于 2014-08-14T00:26:12.630 回答