Odoo 10 selection fields value

Viewed 8454

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.

2 Answers

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 ...

I don't get the question fully, but let me try to answer. Why not just define the selection as method and use it for both situations:

from datetime import datetime
from odoo import models, fields


class MyModel(models.Model):
    _name = 'my.model'

    def month_selection(self):
        return [(1, 'Month1'), (2, 'Month2')]

    def compute_default_value(self):
        selection = self.month_selection()
        # do whatever you want here

    month = fields.Selection(
        selection=month_selection, string='Month',
        default=datetime.now().month, required=True)
Related