This question has been flagged
2 Replies
2662 Views

I am on account_voucher model I want to change the amount field's type into functionnal field, so I did :

class AccountVoucher(orm.Model):

    _inherit="account.voucher"
    _name="account.voucher"

    def _total_payed(self, cr, uid, ids, amount, arg, context=None):
        res = {}
        voucher = self.browse(cr, uid, ids[0], context=context)
        for line in voucher.line_cr_ids:
            res[voucher.id] += line.amount
        return res

    _columns = {
        'amount': fields.function(_total_payed, method=True, string='Amount payed', type='float'),
    }

The purpose is to change it to readonly=True, and make it compute the sum of all the amount payed for all the voucher lines displayed for the current selected customer.

Error Traceback : 

File "/opt/openerp/server/openerp/osv/orm.py", line 3800, in _read_flat res2 = self._columns[f].get(cr, self, ids, f, user, context=context, values=res) File "/opt/openerp/server/openerp/osv/fields.py", line 1145, in get result = self._fnct(obj, cr, uid, ids, name, self._arg, context) File "/opt/openerp/server/openerp/addons/account_payment_bl/account_voucher.py", line 56, in _total_payed res[voucher.id] += line.amount KeyError: 5616 

what's wrong with the key ?

Avatar
Discard
Best Answer

@Yassine, you need to make a loop of ids instead of just taking the first member.  So:

def _total_payed(self, cr, uid, ids, amount, arg, context=None):
        res = {}
        for voucher in self.browse(cr, uid, ids, context=context):

            res[voucher.id] = 0.0
            for line in voucher.line_cr_ids:
                res[voucher.id] += line.amount
        return res

The key error message is caused if ids contains more than one ids.  So, the 2nd and remaining ids wouldn't exist in res because the original code only contain the first member of ids.

Avatar
Discard
Author

Yes ! it worked, many thanks !

Best Answer

Hi Yassine,

Here return value have to be a dictionary in the following format.

res[record.id] = {
                'field_name': value,
            }

In your case you can code like this;-

        res[voucher.id] = {
                'amount': 0.0,
            }

        for line in voucher.line_cr_ids:
            res[voucher.id]['amount'] += line.amount

        return res

       

Avatar
Discard
Author

Thanks Baiju