Skip to Content
Menu
This question has been flagged
2 Replies
6573 Views

Hi, I have written a module where there is a list of expenses. It contains 1.name of expense 2.cost

I want to take a variable and add all expenses into it and display it. How to do that?

-----------------------------

Here is my py code:

class expenditure_records(osv.Model):

_name="expenditure.records"

_columns={

'name':fields.char('Expense name'),

'cost':fields.float('Expenditure cost'),

'expense_id':fields.many2one('expenditure','Expense ID'),

}

Avatar
Discard
Best Answer

Hi Arjun,

You want to get the sum of costs in expense records, that related to an expenditure right? Try like the following:


class expenditure_records(osv.Model):
_name="expenditure.records"
_columns={
'name':fields.char('Expense name'),
'cost':fields.float('Expenditure cost'),
'expense_id':fields.many2one('expenditure','Expense ID'),
}
class expenditure(osv.Model):
_name="expenditure"
def _get_total(self, cr, uid, ids,field_name, args, context=None):
expenditure_pool = self.pool.get('expenditure')
res = {}
for exp_id in self.browse(cr, uid, ids, context=context):
s_total = 0
exp = expenditure_pool.browse(cr,uid, exp_id.id, context=None)
for line in exp.expense_ids:
s_total += line.cost
res[exp_id.id] = s_total
return res
_columns={
'name':fields.char('Expense'),
'date': fields.date(string="Date"),
'expense_ids':fields.one2many('expenditure.records', 'expense_id', string="Expenses"),
'total_expense':fields.function(_get_total, type="float", string="Total Expenses")
}

Avatar
Discard
Best Answer

Don't use list for that, but use dictionary , store expense name in key of dictionary and expense value in  value of dictionary


something like

expense_dict = {'exp1' : 120 , 'exp2' : 350.0, 'exp3' : 500}



then for get total you can do like:


total = 0.0
for value in expense_dict.values():
             total = total + value
print "total expense......",total

      

however if you want sum of list you have inbuilt python method for that, just do like

sum(list)


Note:

you need to make sure your list contains only integer or float values.


Avatar
Discard
Related Posts Replies Views Activity
1
Oct 24
23253
1
Jul 18
4453
0
Sep 24
296
2
Mar 23
2057
1
Nov 18
2000