最近odoo(以前的OpenERP)V8已经发布。在新的 API 方法中引入了装饰器。inmodels.py
方法需要用@api.one
or装饰@api.multi
。
参考odoo 文档我无法确定确切的用途。谁能详细解释一下。
谢谢。
通常,两个装饰器都用于装饰记录样式的方法,其中 ' self
' 包含记录集。让我简要解释一下何时使用@api.one
and @api.multi
:
1 @api.one
.:
装饰一个记录风格的方法,其中' self '应该是一个单例实例。
装饰方法自动循环记录(即,对于记录集中的每条记录,它调用该方法),并用结果创建一个列表。
如果该方法用@returns 修饰,它会连接生成的实例。这样的方法:
@api.one def 方法(self,args):返回 self.name
可以以唱片和传统风格调用,例如::
# recs = model.browse(cr, uid, ids, context)
names = recs.method(args)
names = model.method(cr, uid, ids, args, context=context)
2 @api.multi
.:
装饰一个记录风格的方法,其中 ' self
' 是一个记录集。该方法通常定义对记录的操作。这样的方法:
@api.multi def 方法(self,args):
可以以唱片和传统风格调用,例如::
# recs = model.browse(cr, uid, ids, context)
recs.method(args)
model.method(cr, uid, ids, args, context=context)
何时使用:
如果您使用@api.one,则返回值在列表中。Web 客户端并不总是支持这一点,例如按钮操作方法。在这种情况下,您应该使用 @api.multi 来装饰您的方法,并且可能在方法定义中调用 self.ensure_one() 。
最好使用 @api.multi 和 self.ensure_one() 而不是 @api.one 以避免返回值的副作用。
@api.one:
这个装饰器会自动为您在 RecordSet 的 Records 上循环。Self 被重新定义为当前记录:
@api.one
def func(self):
self.name = 'xyz'
@api.multi:
Self 将是当前没有迭代的 RecordSet。这是默认行为:
@api.multi
def func(self):
len(self)
有关所有 API 的详细说明,您可以参考此链接
@api.model #When the record data/self is not as relevant. Sometimes also used with old API calls.
def model_text(self):
return "this text does not rely on self"
@api.multi #Normally followed by a loop on self because self may contain multiple records
def set_field(self):
for r in self:
r.abc = r.a + r.b
@api.one #The api will do a loop and call the method for each record. Not preferred because of potential problems with returns to web clients
def set_field(self):
self.abc = self.a + self.b