Django渲染DecimalFields

时间:2014-08-13 23:19:19

标签: django django-models sum django-context

我的代码,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()))

和index.html

 {{ total_balance }}
 {{ total_paid }}

我想在所有用户上渲染这些字段的数量,所以我使用" Sum" ,我想要渲染它,但是当我这样做时它不会渲染原始值,由于某种原因我不能指望他们返回{' balance__sum&#39 ;:十进制(' 0.00')} ,我想它的" Sum'"我猜错了

1 个答案:

答案 0 :(得分: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)

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