This question has been flagged
4 Replies
64436 Views

i have following selection fields in my module i want to get string value of selection field. suppose user select 'o' i want to print O - Original please provide me any better solution.

type = fields.Selection([
                        ('o', 'O - Original'),
                        ('a', 'A - Amended')],
                         string="Is this an Original Invoice or Amended Invoice ?"

i have this solution

def get_string_value_of_selection():
    if self.type == 'o':
        value = "O - Original", 
    if self.type == 'a':
        value = "A - Amended"

    print "value = ",value

output

if user select o

value = O - Original
Avatar
Discard
Author Best Answer

it can be archive as follow.

print dict(self._fields['type'].selection).get(self.type)

if user select o

output O - Original


Better answer are welcome.

Avatar
Discard
Best Answer

Lets see some methods in selection fields

console_output = fields.Selection(
[
('console', 'Console'), ​#Consola
('screen', 'Screen'), ​#Pantalla
('both', 'Both') ​#Ambos
], string="Console Output"
)

The original descriptions (Console, Screen...) can be retrieved with the selection property

self._fields['console_output'].selection     

this returns a tuple of values

[('console', 'Console'), ('screen', 'Screen'), ('both', 'Both')]

is most useful with dict()

dict(self._fields['console_output'].selection)

returns

{'console': 'Console', 'screen': 'Screen', 'both': 'Both'}

To retrieve the values translated as seen in the front use get_description() method. 

This method have all information of the field. The self.env is needed to translate the field label

self._fields['console_output'].get_description(self.env)

returns

{'type': 'selection', 'change_default': False, 'company_dependent': False, 'depends': (), 'manual': False, 'readonly': False, 'required': False, 'searchable': True, 'selection': [('console', 'Consola'), ('screen', 'Pantalla'), ('both', 'Ambos')], 'sortable': True, 'store': True, 'string': 'Salida por Consola'}

then, will use the selection key as dict to retrieve the value translated, so

field_info = dict(self._fields['console_output'].get_description(self.env))
field_selection = dict(field_info.get('selection'))
field_label = field_selection.get(self.console_output)


Avatar
Discard
Best Answer
from odoo import api, models, _


def get_selection_label(self, object, field_name, field_value):
  return _(dict(self.env[object].fields_get(allfields=[field_name])[field_name]['selection'])[field_value])


class ResPartner(models.Model):
  _inherit = 'res.partner'

    def my_method(self):
        state_value_translated = get_selection_label(self, 'res.partner', 'state', self.state)
Avatar
Discard

After 2 hour of searching, I've found your solution, thank you, I'm exhausted