odoo - 2个字段的many2one字段组合的显示名称

odoo - display name of many2one field combination of 2 fields

在我的模块中,我有以下 many2one 字段: 'xx_insurance_type': fields.many2one('xx.insurance.type', string='Insurance')

其中 xx.insurance.type 如下:

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 %')
    }

我知道 many2one 字段将 name 字段作为其显示名称,但我想让它使用 nameinsurance_percentage 的组合以 name + " - " + insurance_percentage + "%"

的形式

我读到最好覆盖 get_name 方法,所以我尝试了以下方法:

def get_name(self,cr, uid, ids, context=None):
    if context is None:
        context = {}
    if isinstance(ids, (int, long)):
        ids = [ids]

    res = []
    for record in self.browse(cr, uid, ids, context=context):
         name = record.name
         percentage = record.insurance_percentage
         res.append(record.id, name + " - " + percentage + "%")
    return res

并将其放入 ÌnsuranceType` class 中。 因为什么都没发生: 我是否必须将它放在包含该字段的主要 class 中?如果是这样,是否有其他方法可以做到这一点,因为这可能也会改变其他 many2one 字段的显示方式?

如果您不想更改与模型 xx.insurance.type 相关的其余 many2one 的显示名称,您可以在 XML 视图中添加上下文以您要修改其显示名称的many2one

<field name="xx_insurance_type" context="{'special_display_name': True}"/>

然后,在您的 name_get 函数中:

def name_get(self, cr, uid, ids, context=None):
    if context is None:
        context = {}
    if isinstance(ids, (int, long)):
        ids = [ids]
    res = []
    if context.get('special_display_name', False):
        for record in self.browse(cr, uid, ids, context=context):
            name = record.name
            percentage = record.insurance_percentage
            res.append(record.id, name + " - " + percentage + "%")
    else:
        # Do a for and set here the standard display name, for example if the standard display name were name, you should do the next for
        for record in self.browse(cr, uid, ids, context=context):
            res.append(record.id, record.name)
    return res
@api.depends('name', 'insurance_percentage')
    def name_get(self):
        res = []
        for record in self:
            name = record.name
            if record.insurance_percentage:
                name = '[' + record.insurance_percentage+ ']' + name
            res.append((record.id, name))
        return res