如何在函数内部调用函数?Odoo9验证

How to call a function inside a function ?Odoo9 Validation

我在 product.pricelist.item

中添加了一个布尔字段
class product_pricelist_item(models.Model):
    _inherit = 'product.pricelist.item'

    myfield = fields.Boolean(string="CheckMark")

现在 product.pricelist.item.

中有多行

(验证) 我希望用户不允许 True 多个 myfield 一个字段一次可以 True

我在 product.pricelist.item 中尝试这样做,方法是给它一个计数器并向计数器传递 myfields 的数量,即 True.

但这给了我错误。

global name '_get_counter' is not defined

def _get_counter(self):
    for r in self:
        p=[]
        p= r.env['product.pricelist.item'].search_read([('myfield', '=', True)], ['myfield'])
        counter = len(p)
    return counter

@api.constrains('myfield')
def _check_myfield(self):
    counter = _get_counter(self)
    for r in self:
        if counter > 1:
            raise exceptions.ValidationError("Multiple myfield In a PriceList of a Product is not allowed.")

现在第二个问题是:-

当您创建价目表项目并单击保存在价目表中时,它不会反映数据库中的数据。当您点击价目表保存时,它会反映数据...为什么会这样?

使用self我们可以调用当前class的方法。

尝试使用以下代码:

替换代码

counter = _get_counter(self)

counter = self._get_counter()

_get_counter 中的循环不影响结果,并且搜索不依赖于记录,因此您可以使用:

def _get_counter(self):

    pricelist_obj = self.env['product.pricelist.item']
    counter = len(pricelist_obj.search_read([('myfield', '=', True)], ['myfield']))
    return counter

@api.constrains('myfield')
def _check_myfield(self):

    counter = self._get_counter()
    if counter > 1:
        raise exceptions.ValidationError("Multiple myfield In a PriceList of a Product is not allowed.")