@ api.one,@ api.multi和@ api.model有什么区别? [英] What is difference between @api.one, @api.multi and @api.model?

查看:268
本文介绍了@ api.one,@ api.multi和@ api.model有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Odoo中的@api.one@api.multi@api.model感到困惑.

I am confused regarding @api.one, @api.multi, and @api.model in Odoo.

这三者之间有什么区别,它们的用例是什么?

What are the differences between the three and what are their use cases?

推荐答案

api.one用于仅在一条记录上调用method的情况.确保使用api.one装饰器调用方法时没有多个记录.假设您有记录partner = res.partner(1,).它只有一条记录,并且有一个示例(在res.partner中):

api.one is meant to be used when method is called only on one record. It makes sure, that there are no multiple records when calling method with api.one decorator. Let say you got record partner = res.partner(1,). It is only one record and there is method for example (in res.partner):

@api.one
def get_name(self):
    return self.name #self here means one record

像这样调用它:

partner.get_name()

但是如果还有更多记录,例如partners = res.partner(1, 2,)

But if there would be more records, like partners = res.partner(1, 2,)

调用它会发出警告,告诉您只能在一条记录上调用它.对于多个记录,使用api.multi,其中self是记录集,并且可以遍历所有记录以执行某些操作.例如:

calling it, would raise a Warning, telling you that you can only call it on one record. For multiple records api.multi is used, where self is recordset and it can be iterated through all records to do something. For example:

@api.multi
def get_partner_names(self):
    names = []
    for rec in self:
        names.append(rec.name)
    return ', '.join(names)

api.model被认为是在您需要对模型本身进行某些操作并且不需要修改/检查某些精确的模型记录时使用的.例如,可能存在返回有关模型结构的元信息或一些辅助方法等的方法.在文档中也称此api从旧api迁移时很好用,因为它礼貌地"将代码转换为新api .同样以我自己的经验,如果您需要返回某些内容的方法,则model装饰器非常有用. api.one返回空列表,因此在应该使用api.one on方法时应该返回某些内容的情况下,可能会导致意外行为.

And api.model is considered to be used when you need to do something with model itself and don't need to modify/check some exact model's record/records. For example there could be method that returns some meta info about model's structure or some helper methods, etc. Also in documentation it is said that this api is good to use when migrating from old api, because it "politely" converts code to new api. Also in my own experience, if you need method to return something, model decorator is good for it. api.one returns empty list, so it might lead to unexpected behavior when using api.one on method when it is supposed to return something.

更多信息: http://odoo -new-api-guide-line.readthedocs.org/en/latest/decorator.html

这篇关于@ api.one,@ api.multi和@ api.model有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆