How can I make a calculation in the view?

62 views
Skip to first unread message

greenpoise

unread,
May 19, 2016, 12:13:47 AM5/19/16
to web2py-users
I have seen examples on how to calculate on DAL level using lambda. Could someone post an example (or point me to) of calculating values in the view? after an sql retrieval? or sql in the view? 


Thanks

黄祥

unread,
May 19, 2016, 1:11:40 AM5/19/16
to web2py-users
just do like usual in controller
e.g.
controllers/default.py
def report_investor():
choose_investor = request.args(0)
# query
query_account = (db.account.investor == choose_investor)

# row
rows_account = db(query_account).select(orderby = ~db.account.id)

return dict(rows_account = rows_account)

views/default/report_investor.html
<table class = 'detail'>
<tbody>
<th class = 'border'>
{{=SPAN(T('P/L') ) }}
<br />
{{=SPAN(T('P/L (%)') ) }}
</th>
<th class = 'border'>
{{=SPAN(T('Net P/L') ) }}
<br />
{{=SPAN(T('Net P/L (%)') ) }}
</th>
</tr>

{{for row_account in rows_account:}}
<tr>
{{
profit_loss_value = row_account.balance - row_account.subscription_amount
profit_loss_percentage = (profit_loss_value / row_account.subscription_amount) * 100 if row_account.subscription_amount > 0 else 0
}}
<td class="text-right border">
{{=SPAN('%s %s' % (row_account.product.currency.symbol, locale.format("%.2f", profit_loss_value, grouping = True) ), _class = 'red' if profit_loss_value <= 0 else 'green') }}
<br />
{{=SPAN('%s %%' % (locale.format("%.2f", profit_loss_percentage, grouping = True) ), _class = 'red' if profit_loss_percentage <= 0 else 'green') }}
</td>
{{
net_subscription = row_account.subscription_amount + row_account.subscription_fee + row_account.redemption_fee
net_profit_loss_value = row_account.balance - net_subscription
net_profit_loss_percentage = (net_profit_loss_value / net_subscription) * 100 if net_subscription > 0 else 0
}}
<td class="text-right border">
{{=SPAN('%s %s' % (row_account.product.currency.symbol, locale.format("%.2f", net_profit_loss_value, grouping = True) ), _class = 'red' if net_profit_loss_value <= 0 else 'green') }}
<br />
{{=SPAN('%s %%' % (locale.format("%.2f", net_profit_loss_percentage, grouping = True) ), _class = 'red' if net_profit_loss_percentage <= 0 else 'green') }}
</td>
</tr>
{{pass}}
</tbody>
</table>

best regards,
stifan

Anthony

unread,
May 19, 2016, 6:09:52 AM5/19/16
to web...@googlegroups.com
Though generally it is good to minimize the logic in views, as they are more difficult to read, test, and debug. So, prefer moving such calculations to the controller, or at least to a function that is simply called from the view.

Anthony

greenpoise

unread,
May 19, 2016, 2:04:18 PM5/19/16
to web2py-users
Thanks a million.

greenpoise

unread,
May 19, 2016, 2:04:53 PM5/19/16
to web2py-users
I see. Thanks Anthony
Reply all
Reply to author
Forward
0 new messages