Odoo 10 selection fields value

Serdar Eren picture Serdar Eren · Sep 20, 2017 · Viewed 7.8k times · Source

How can i get selection fields value in odoo 10?

def compute_default_value(self):
    return self.get_value("field")

I tried this,

def compute_default_value(self):
   return dict(self._fields['field'].selection).get(self.type)

Also tried this,but it is not working. Please help me, i could not find the solution.

Thank you.

Answer

tidylobster picture tidylobster · Sep 21, 2017

You can do this in a following manner:

self._fields['your_field']._desription_selection(self.env)

This will return the selection list of pairs (value, label).

If you just need possible values, you can use get_values method.

self._fields['your_field'].get_values(self.env)

But it's not a common way. Most of the time people define selections differently and then use those definitions. For example, I commonly use classes for those.

class BaseSelectionType(object):
    """ Base abstract class """

    values = None

    @classmethod
    def get_selection(cls):
        return [(x, cls.values[x]) for x in sorted(cls.values)]

    @classmethod
    def get_value(cls, _id):
        return cls.values.get(_id, False)


class StateType(BaseSelectionType):
    """ Your selection """
    NEW = 1
    IN_PROGRESS = 2
    FINISHED = 3

    values = {
        NEW: 'New',
        IN_PROGRESS: 'In Progress',
        FINISHED: 'Finished'
    }

You can use this class wherever you want, just import it.

state = fields.Selection(StateType.get_selection(), 'State')

And it's really handy to use those in the code. For example, if you want to do something on a specific state:

if self.state == StateType.NEW:
    # do your code ...