Odoo - 从many2one字段获取值

3

我的代码:

class SaleOrder(osv.Model):
    _inherit = 'sale.order'

    _columns = {
        'xx_delivery_date': fields.date(string='Delivery date'),
        'xx_payment_method': fields.many2one('xx.payment.method',
                                             string='Payment method'),
        'xx_insurance_type': fields.many2one('xx.insurance.type', string='Insurance')
    }

    def _amount_insurance(self, cr, uid, val1, context=None):
        val = 0.0
        insurance_chosen = self.pool.get('xx.insurance.type').browse(cr, uid, insurance_percentage.id,context=context)
        val = val1*insurance_chosen/100
        return val

class InsuranceType(osv.Model):
    _name='xx.insurance.type'

    _columns = {
        'name' : fields.char(size=128, string = 'Name'),
        'sale_ids': fields.one2many('sale.order', 'xx_insurance_type', string = 'Sale orders'),
        'insurance_percentage' : fields.float('Insurance cost in %')
    }
我是一名有用的助手,以下是您需要翻译的内容:

我正在尝试获取“insurance_percentage”字段中的浮点数,并将此百分比添加到val1中。

目前我的代码的结果是:

'Global name insurance_percentage not defined,

所以我必须想办法告诉函数从 InsuranceType 类中获取变量,但我不知道如何做到这一点。

1个回答

1

对于many2one字段,我们需要先获取该记录的ID,然后使用该ID浏览该记录并从中取出所需值。

尝试使用以下代码:

def _amount_insurance(self, cr, uid, ids, val1, context=None):
    val = 0.0
    for insurance in self.browse(cr, uid, ids,context=context):
        if insurance.xx_insurance_type:
            val = (val1 * (insurance.xx_insurance_type.insurance_percentage/100))
    return val

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,