2011-11-01 57 views
0

我的注释(sum())函数有一个小问题。现在我想要它做的是在列表中列出给定计划中所有到期日的总数。它为第一个做。下面的代码:annotate()添加超过需要

#get the invesments maturing this year 
     for p in plans: 
      cur_inv = Investment.objects.all().filter(plan = p).order_by('financial_institution').filter(maturity_date__year = current_year) 
      nxt_inv = Investment.objects.all().filter(plan = p).order_by('financial_institution').filter(maturity_date__year = next_yr) 
      thr_inv = Investment.objects.all().filter(plan = p).order_by('financial_institution').filter(maturity_date__year = thr_yr) 
      fr_inv = Investment.objects.all().filter(plan = p).order_by('financial_institution').filter(maturity_date__year = fr_yr) 
      fv_inv = Investment.objects.all().filter(plan = p).order_by('financial_institution').filter(maturity_date__year = fv_yr) 

      for inv in cur_inv: 
       total += inv.amount or 0 
      for inv in cur_inv: 
       total_m += inv.maturity_amount or 0 

      for inv in nxt_inv: 
       total2 += inv.amount or 0 
      for inv in nxt_inv: 
       total_m2 += inv.maturity_amount or 0 

      for inv in thr_inv: 
       total3 += inv.amount or 0 
      for inv in thr_inv: 
       total_m3 += inv.maturity_amount or 0 

      for inv in fr_inv: 
       total4 += inv.amount or 0 
      for inv in fr_inv: 
       total_m4 += inv.maturity_amount or 0 

      for inv in fv_inv: 
       total5 += inv.amount or 0 
      for inv in fv_inv: 
       total_m5 += inv.maturity_amount or 0 

#Calculate the holding totals with each company 
      total_list = p.investment_set.filter(maturity_date__gte= '%s-1-1' % current_year).values('financial_institution__abbr').annotate(Sum('maturity_amount')).order_by('financial_institution__abbr') 
      gtotal = total_m + total_m2 + total_m3 + total_m4 + total_m5 

      plan_list.append({ 
       'plan':p, 
       'investment': cur_inv, 
       'nxt_inv': nxt_inv, 
       'thr_inv': thr_inv, 
       'fr_inv': fr_inv, 
       'fv_inv': fv_inv, 
       'total_list': total_list, 
       'grand': gtotal, 
      }) 

我唯一的问题现在是,当它进入到下一步的计划,但它仍然不是回到0

添加到总计,难道我失去了一些东西?

任何帮助,将不胜感激。

感谢

+1

您似乎编辑了太多的代码来正确地帮助您。 'total_m *'变量来自哪里? –

+0

@ChrisPratt我会更新它。 – TheLifeOfSteve

回答

1

您使用+=total_m*增值经销商,但从未将其复位0在循环。他们不会自动重置,只是因为新的迭代已经开始。

FWIW,你应该尝试在这里优化你的代码。您正在生成6 * len(计划)查询,这可能相当昂贵。

+0

谢谢,这工作......我会考虑优化我的查询。 – TheLifeOfSteve