odoo - display name of many2one field combination of 2 fields

妖精的绣舞 提交于 2019-11-27 02:58:30

问题


In my module i have the following many2one field: 'xx_insurance_type': fields.many2one('xx.insurance.type', string='Insurance')

where xx.insurance.type is the following:

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

I know the many2one field takes the name field as its display name but I would like to have it use the combination of name and insurance_percentage in the form of name + " - " + insurance_percentage + "%"

I read it is best to overwrite the get_name method so I tried the following:

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

and placed this inside the ÌnsuranceType` class. Since nothing happened: Do i have to place it inside the main class containing the field? If so, is there an other way to do this since that will probably also change the display ways of the other many2one fields?


回答1:


If you don't want to alter the display name of the rest of the many2one related to the model xx.insurance.type, you can add a context in the XML view to the many2one whose display name you want to modify:

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

And then, in your name_get function:

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


来源:https://stackoverflow.com/questions/31724556/odoo-display-name-of-many2one-field-combination-of-2-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!