Bỏ qua để đến Nội dung
Menu
Câu hỏi này đã bị gắn cờ
2 Trả lời
7776 Lượt xem

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'),

}

Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

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")
}

Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

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.


Ảnh đại diện
Huỷ bỏ
Bài viết liên quan Trả lời Lượt xem Hoạt động
1
thg 10 24
25671
1
thg 7 18
5312
0
thg 3 25
1856
2
thg 3 23
3707
1
thg 11 18
2639