如何仅在 Odoo 8 中满足某些条件时才计算字段?

How to make a field computed only if some condition is fulfilled in Odoo 8?

在 Odoo 8 中是否有任何方法可以创建一个仅在满足某些条件时才计算的字段,否则用户将能够设置其值?

例子

我有一个名为 box 的模型,它有一个名为 value.

的浮点字段

想象一下,一个盒子里面可以有几个盒子,每个盒子都有自己的价值。

所以我们有一个名为 child_ids 的 one2many 字段指向 box 和一个名为 parent_id 的 many2one 也指向框。

现在我想要以下行为:用户可以设置内部没有任何框的框的 value 字段(这意味着,childs_idsFalse),但是,如果框内至少有一个框(这意味着 childs_ids 不是 False),则必须计算 value 字段它将是其子项 value.

的总和

有没有人知道如何实现这种行为?

我放了我的代码,但它不起作用(value 的值总是被重置为 0):

class box(models.Model):
    _name='box'

    @api.one
    @api.depends('child_ids', 'child_ids.value')
    def _compute_value(self):
        if self.child_ids:
            self.value = sum(
                [child.value for child in self.child_ids])

    def _set_value(self):
        pass

    parent_id = fields.Many2one(comodel_name='box',
                                string='Parent Box')

    child_ids = fields.One2many(comodel_name='box',
                                inverse_name='parent_id',
                                string='Boxes inside')

    value = fields.Float(
        string='Value',
        compute='_compute_value',
        inverse='_set_value',
        store=False,
        required=True,
        readonly=True,
        states={'draft':[('readonly',False)]},
    )

在模型中

computed_field = fields.Char(compute='comp', inverse='inv', store=True)
boolean_field = fields.Boolean()

@api.one
def comp(self):
    ...

@api.one
def inv(self):
    ...

在视图中

<field name="boolean_field" />
<field name="computed_field" attrs="{'readonly': [('boolean_field','=',True)]}" />

编辑:

现在您的示例更加清晰了,我认为您应该更改以下内容:

valuestore 参数设置为 True 而不是 False 并删除 inverse,在您的情况下,您不需要。

那你还需要2个字段

value_manual = fields.Float()
manual = fields.Boolean(compute='_is_manual', default=True)

@api.one
@api.depends('child_ids')
def _is_manual(self):
    self.manual = len(self.child_ids) == 0

加上

@api.one
@api.depends('child_ids', 'child_ids.value')
def _compute_value(self):
    if self.child_ids:
        self.value = sum(
            [child.value for child in self.child_ids])
    else:
        self.value = self.value_manual

在视图中:

<field name="manual" invisible="1" />
<field name="value" attrs="{'invisible': [('manual','=',True)]}" />
<field name="value_manual" attrs="{'invisible': [('manual','=',False)]}" />

可能有另一种解决方案可以避免这个双字段,也许使用相反的方法,但我不确定。