如何在html django中聚合

时间:2011-03-07 17:39:06

标签: python django django-templates django-views

写了一个excel格式的html指标来表示明智的日期计数

def get_detail(usr,dt):
   res = Dataset.objects.filter(user = usr, date = dt).values('expense')
   try :
      output=res[0]['expense']
   except IndexError:
      output=" "
   return output

上面的代码是一个函数

def metrics_new(request, year = None, month = None):
   import calendar
   from datetime import *
   from dateutil.relativedelta import relativedelta 



   m = Profile.objects.filter(lead = 'sushanth' ,status='A')
   now=datetime.today()

   if not year:
      year = now.year
   if not month:
      month = now.month


   year = int(year)
   month = int(month)
   d = calendar.mdays[month]

   out_txt="<TABLE id=\"myTable\" class=\"tablesorter\">\n"
   out_txt += "<THEAD>"
   out_txt += "<TR>"

   out_txt += "<TH> LDAP </TH>"
   for i in xrange(1,d):
       date_format = now.replace( year = year , month = month , day = i )
       out_txt += "<TH>" + str(date_format) + "</TH>"
   out_txt += "</TR>\n"
   out_txt += "</THEAD>"
   s_no = 0
   for fetch in m:
      out_txt += "<TR>"
      ld = fetch.user
      out_txt += "<TD>" + str(ld) + "</TD>"
      for i in xrange(1,d):
          date_format = now.replace( year = year , month = month , day = i )

          out_txt += "<TD>" + str(get_details(ld,date_format)) + "</TD>"
      out_txt += "<TR>\n"
   out_txt +="</TABLE>\n"
   try:
    cal_date = date(int(year), int(month), 1)
   except ValueError:
    raise Http404
   prev_month = (cal_date + relativedelta(months = -1))
   next_month = (cal_date + relativedelta(months = +1))




   return render_to_response('metrics.html', {'table':out_txt,
                                'prev_month':prev_month,'next_month': next_month, }, 
                             context_instance = RequestContext(request))

我已经生成了表及其工作,如何汇总每行的费用

输出:

user 2011-02-01 2011-02-02 2011-02-03 2011-02-04.......2011-02-28
 x     2          4          5                           2
 y     1          2
 z                            4 

但我希望以下面的格式

    user 2011-02-01 2011-02-02 2011-02-03 2011-02-04.......2011-02-28 total
 x     2          4          5                           2             13
 y     1          2                                                     3
 z                            4                                         4
  • 这里我想汇总数据 结束?

  • 有什么最好的办法吗?

提前致谢

1 个答案:

答案 0 :(得分:0)

从视图中删除所有HTML创建代码。

视图需要为模板创建所需的变量,模板应该处理格式化。也许创建一个用户列表,并为每个用户创建一个长度为calendar.mdays [month]的列表,其中包含该用户的范围和一个sum变量。

users_list = [{'username':'x', 'expense_list':[2,4,5,0,0,0,2], 'sum':13}, ...]

当您在视图中执行此操作并拥有每个用户的费用列表时,计算总和应该就像

一样简单
user['sum'] = sum(user['expense_list'])

然后你的模板代码应该很简单:

{% for user in users_list %}
    <tr>
    <td>{{ user.username }}</td>
    {% for expense in user.expense_list %}
        <td>{{ expense }}</td>
    {% endfor %}
    <td>{{ user.sum }}</td>
    </tr>
{% endfor %}