cgs
cgs

Reputation: 342

Odoo: Access field by it's name (given as string)

I have a model, where I want to access a field, given by a string. Example:

def test(self):
    field = 'name'
    name = getattr(self, field)

This works fine - name is set to self.name. But then I want to access a related field:

def test2(self):
    field = 'partner_id.name'
    name = getattr(self, field)

That doesn't work (because 'partner_id.name' does not exist on self). Any idea how to do it right?

Upvotes: 2

Views: 1755

Answers (3)

cgs
cgs

Reputation: 342

I also came across another solution, inspired by the mail template system:

from openerp.tools.safe_eval import safe_eval as eval

def test2(self):
    field = 'partner_id.name'
    field = 'object.' + field
    name = eval(field, {'object': self})

Upvotes: 0

Kenly
Kenly

Reputation: 26738

You need to use the object that contain partner_id.name

def test2(self):
    field = 'name'
    object = self.pool.get('res.partner').browse(cr, uid, self.partner_id.id)#v7
    #object = self.env['res.partner'].browse(self.partner_id.id)#v8
    name = getattr(object, field)

Upvotes: 1

Ludwik Trammer
Ludwik Trammer

Reputation: 25052

getattr doesn't support the dot notation, only simple attribute names. You can however create a simple function that does:

def getfield(model, field_name):
    value = model
    for part in field_name.split('.'):
        value = getattr(value, part)
    return value

You would use it like this:

def test2(self):
    field = 'partner_id.name'
    name = getfield(self, field)

Upvotes: 5

Related Questions