How to format the result of a sum()

42 views
Skip to first unread message

mke...@halstead.com

unread,
Mar 30, 2017, 9:58:01 PM3/30/17
to web2py-users
How does one apply formatting to a field which is not defined in a table, but rather the result of a sum() operation?  

Below, the field 'price' is formatted in the table definition as currency, and displays in forms with appropriate currency symbol and thousands separators.  However, after the sum() operation is applied, the resulting computed field no longer has access to that formatting function.

---------------
simple example -  in controller...

def func()
  type = db.table1.type
  price = db.table1.price

  rows = db().select(type, price.sum(), groupby=type)

  tbl = SQLTABLE(rows)

return dict(tbl=tbl)
---------------

I'm currently using an SQLTABLE but could alternatively use an SQLFORM.grid instead if that provides a better solution.  I can't seem to find a way to attach a lamda function to the computed field in order to provide formatting for that specific field in the form/grid.

Thanks.





黄祥

unread,
Mar 31, 2017, 1:24:55 AM3/31/17
to web2py-users
pls try in views
e.g.
for float :
{{=DIV('Rp. %s' % (locale.format("%.2f", total_sum_sales, grouping = True) ) ) }}
for integer
{{=DIV('%s' % (format(total_sum_sales, ",d").replace(",", ".") ) ) }}

best regards,
stifan

mke...@halstead.com

unread,
Apr 1, 2017, 10:46:00 AM4/1/17
to web2py-users
Thanks for this, but is there no way to apply this formatting in the controller?  

My views are very simple, with tables being rendered simply with {{=tbl}}, so unless I'm missing something, I don't think I really have any way to apply the DIV as you suggested.

Thanks.

黄祥

unread,
Apr 1, 2017, 5:46:18 PM4/1/17
to web2py-users
of course you can do it in controller
e.g.
def index():
import locale
sum = db.log.severity.sum()
sum_result = db().select(sum).first()[sum]
# float
sum_result_formatted = DIV('%s' % (locale.format("%.2f", sum_result, grouping = True) ) )
# int
#sum_result_formatted = DIV('%s' % (format(sum_result, ",d").replace(",", ".") ) )
return dict(sum_result_formatted = sum_result_formatted)

best regards,
stifan
Reply all
Reply to author
Forward
0 new messages