name_get Helper

Helper method for more convenient name_get overriding

Andrius Laukavičius

When overriding name_get for Odoo models, usual case is that you need to add some extra field values on display. It can be direct value (on model) or related model's value. 

It usually goes like this (taken from Odoo standard source):

@api.multi
@api.depends('name', 'brand_id')
def name_get(self):
    res = []
    for record in self:
        name = record.name
        if record.brand_id.name:
            name = record.brand_id.name + ' / ' + name
        res.append((record.id, name))
    return res

This can get quite tedious, if you need to override name_get method on mutliple models. To reduce boiler plate code, we can use a function that handles this pattern and in turn simplifies name_get overriding.

So I (and my colleague) created python helper package called footil, which consists of various helper functions. One of them is called generate_names.

It can be used for other similar cases, though it fits name_get  quite well. Here you provide pattern for display name and on which records to generate list of tuple. So to rewrite same code from above, we can simplify it like this:

@api.multi
@api.depends('name', 'brand_id')
def name_get(self):
    return generate_names(
        {'pattern': '{brand_id.name} / {name}', 'objects': self})

By default generate_names strips falsy values, so in cases when optional attribute is false, it will not be displayed.

In name_get cases, usually that's what you want. If you want to keep even falsy ones, you can call generate_names with extra key:

generate_names({'my_pattern', 'objects': myrecords, 'strip_falsy': False})

If case we have recordset with two records where one consists of both truthy values and another with only name being truthy, returned result would look like this (first item in tuple, is record ID):

[(1, 'my_brand_name / my_name'), (2, 'my_name_2')]

Generate names can be found in footil package module formatting. To install it, you can simply type:

pip3 install footil

Or you can install it directly from source. But beware, that footil is still in beta (as of writing, it has 0.12.0 version). So it could still have some backwards incompatible changes.