2017-02-20 40 views
1

我有這樣的模式:我如何可以總結一個Django模型的內容

class Transfer(models.Model): 
     transfer_code = models.CharField(max_length=30, blank=True, null=True) 
     sender_name = models.CharField(max_length=30, blank=True, null=True) 
     amount = models.IntegerField(blank=True, null=True) 
     recipient_name = models.CharField(max_length=30, blank=True, null=True) 
     time_sent = models.DateTimeField(auto_now_add=True, auto_now=False) 
     received = models.BooleanField(default=False) 
     time_received = models.DateTimeField(auto_now_add=False, auto_now=False, null=True) 

     def __unicode__(self): 
      return self.transfer_code 

這是我的看法,我想以計算表總量:

def listtransfersall(request): 
    title = 'ALL TRANSFERS' 
    queryset = Transfer.objects.all() 
    for instance in queryset: 
     total = 0 
     total += instance.amount 
     print total 

    context = { 
    "title": title, 
    "queryset": queryset, 
    "total": total, 
    } 
    return render(request, "listtransfersall.html",context) 

這版畫表中的金額單獨。 如何獲得總數並將其分配給總變量?

回答

3

在你貼的代碼,你設定每次total = 0通過循環

for instance in queryset: 
    total = 0 
    total += instance.amount 
    print total 

移動該行的循環之外,這將工作,你希望的方式。

稍微好一點的會得到一個values_list,總結說:

amounts = Transfer.objects.values_list('amount', flat=True) 
total = sum(amounts) 

更妙的是讓數據庫做的工作,並使用Sum聚合:

from django.db.models import Sum 
total = Transfer.objects.aggregate(Sum("amount")) 

documentation有關聚合的更多信息,請參閱

1

您可以使用annotate。在你的情況,試試這個:

from django.db.models import Sum 

queryset = Transfer.objects.annotate(total_amount=Sum('amount')) 

,然後在模板中使用:

queryset.total_amount 
1

我不知道我完全瞭解你的問題,但我認爲你的問題是,您聲明total = 0在你的循環中。因此,在每次迭代中添加值instance.amount之前,它總是爲0。

必須聲明total = 0你進入你的循環之前,像這樣

total = 0 
for instance in queryset: 
    total += instance.amount 
print total 

該代碼將增加instance.amounttotal變量和打印的總價值。

相關問題