宜兴通达竭诚为您服务。

通达科技 - 宜兴电脑维护及IT服务外包服务商

Model Methods and Decorators
  • 上传者: Administrator
  • 上传时间:2023年11月14日 03时24分57秒
摘要:
* Model Methods and Decorators ** *** * 模型方法和装饰 ** *** The class in Odoo models contains field declarations as well as business logic methods. The ......
正文 相关文章 请喝咖啡

    Model Methods and Decorators

    模型方法和装饰

    The class in Odoo models contains field declarations as well as business logic methods. The method defined for a button click is one example of a simple type of method.

    Odoo模型中的类包含字段声明以及业务逻辑方法。为按钮单击定义的方法是简单方法类型的一个示例。

    For example, clicking the confirm button in a form view changes the state from 'Draft' to 'Confirmed.'

    例如,单击表单视图中的确认按钮会将状态从“草稿”更改为“已确认”

    The function will first be declared from the XML:

    函数将首先从XML中声明: button name="action_confirm" string="Confirm" type="object"/

    The form view will include a 'Confirm' button, whose python action is specified in the button's name attribute (action confirm).

    表单视图将包含一个“确认”按钮,其python操作在按钮的name属性(actionconfirm)中指定。

    state=fields.Selection([(draft,'Draft'),(confirmed,'Confirmed')],default='draft')

    def action_confirm(self):

       self.state = 'confirmed'

    In this case, action confirm is a Python method with self as an argument.'self,' the first argument method of Odoo models, can take additional arguments.

    在这种情况下,actionconfirm是一个以self为参数的Python方法。Odoo模型的第一个参数方法“self”可以接受其他参数。

    Decorators.

    装饰

    Decorators allow you to change the behavior of a method. It simply adds functionality to a function before returning it.

    装饰器允许您更改方法的行为。它只是在返回函数之前为函数添加功能。

    @api.autovaccum

    The daily vacuum cron job calls the methods decorated by this decorator (model ir.autovacuum). It is used for tasks that do not require a specific cron job.

    每日的vacuum cron作业调用由这个装饰器(模型ir.autovacuum)装饰的方法。它用于不需要特定cron作业的任务。

    @api.constrains(*args)

    Fields from the particular model are the arguments given to the decorator. When any of the fields are altered, the function will be called.

    特定模型中的字段是给装饰器的参数。当任何字段被更改时,函数将被调用。

    @constrains only support field names, not dotted fields(related fields, Eg:partner_id.city).

    @constrains 仅支持字段名,不支持虚线字段(相关字段,例如:partner_id.city)。

    @constrains will only be executed if the defined fields in the decorated method are used in the model's create or write function.

    @constrains 只有在模型的创建或写入函数中使用装饰方法中定义的字段时,才会执行约束。

    It implies that fields won't cause the function to be called during record generation if they don't exist in the view.

    这意味着,如果字段在视图中不存在,则不会在记录生成期间调用函数。

    An override of create is required to ensure that a constraint is always active.

    需要覆盖create以确保约束始终处于活动状态。

    @api.depends

    This decorator can be used to declare the field dependencies of the "compute" method.Each argument must be a string made up of a dot-separated list of field names:

    此装饰器可用于声明“compute”方法的字段依赖关系。每个参数必须是一个由点分隔的字段名列表组成的字符串:

    pname = fields.Char(compute='_compute_pname')

    @api.depends('partner_id.name', 'partner_id.is_company')

    def _compute_pname(self):

        for record in self:

            if record.partner_id.is_company:

                record.pname = (record.partner_id.name or "").upper()

            else:

                record.pname = record.partner_id.name

    @api.depends_context(*args)

    This decorator can be used to declare the context dependencies of a non-stored "compute" method. Each passed argument is a key in the context dictionary.

    此装饰器可用于声明非存储的“计算”方法的上下文依赖关系。每个传递的参数都是上下文字典中的一个键。

    price = fields.Float(compute='_compute_product_price')

    @api.depends_context('pricelist')

    def _compute_product_price(self):

        for product in self:

            if product.env.context.get('pricelist'):

                pricelist = self.env['product.pricelist'].browse(product.env.context['pricelist'])

            else:

                pricelist = self.env['product.pricelist'].get_default_pricelist()

            product.price = pricelist.get_products_price(product).get(product.id, 0.0)

    @api.model

    Decorate a record-style method in which self is a recordset but the contents of its are irrelevant; only its model is.

    装饰一个记录风格的方法,其中self是一个记录集,但其内容无关紧要;只有它的模型是。

    @api.model

    def method(self, args):

        //Add your method here

    @api.model_create_multi

    Decorate a method with a list of dictionaries if it creates several records. It is referred to as a list of dictionaries.

    如果方法创建了多条记录,则使用字典列表对其进行装饰。它被称为字典列表。

    record = model.create(vals)

    records = model.create([vals, ...])

    @api.onchange(*args)

    The view's fields will be passed as arguments to the 'onchange' decorator. The method will be called when the view's field is modified. The method is called on a pseudo-record that contains the form's values. The field assignments on that record are automatically returned to the client.

    视图的字段将作为参数传递给'onchange'装饰器。当修改视图的字段时,将调用该方法。该方法在包含表单值的伪记录上调用。该记录上的字段分配将自动返回给客户端。

    @api.onchange('partner_id')

    def _onchange_partner(self):

        self.message = "Dear %s" % (self.partner_id.name or "")

        return {

           'warning': {'title': "Warning", 'message': "What is this?",'type': 'notification'},}

    @onchange only supports simple field names, relational fields are not supported(partner_id.city)

    @onchange 只支持简单的字段名,不支持关系字段(partner_id.city)

    Because @onchange returns a recordset of pseudo-records, trying to call any of the CRUD methods (create(), read(), write(), unlink()) on this recordset results in undefined behavior, because the records may not yet exist in the database.

    因为@onchange返回伪记录的记录集,所以尝试调用此记录集上的任何CRUD方法(create()、read()、write()、unlink())都会导致未定义的行为,因为这些记录可能尚未存在于数据库中。

    Instead, we could use the update() method or easily set the field as in this example.

    相反,我们可以使用update()方法,或者像本例中那样轻松设置字段。

    Onchange cannot be used to modify a one2many or many2many field.

    Onchange 不能用于修改一对多或多对一字段。

    @api.ondelete(*, at_uninstall)

    Mark a method to be executed during unlink().

    标记要在unlink()期间执行的方法。

    The methods decorated with @ondelete should raise an error if certain conditions are met, as well as the method should be named either _unlink_if_<condition> or _unlink_except_ <not_condition>.

    如果满足某些条件,用@ondelete修饰的方法应引发错误,并且该方法应命名为_unlink_if_<condition>或_unlink_except_<not_condition>。

    @api.ondelete(at_uninstall=False)

    def _unlink_if_user_inactive(self):

        if any(user.active for user in self):

            raise UserError("Can't delete an active user!")

    # same as above but with _unlink_except_* as method name

    @api.ondelete(at_uninstall=False)

    def _unlink_except_active_user(self):

        if any(user.active for user in self):

            raise UserError("Can't delete an active user!")

    Parameters:

    参数:

    at_uninstall (bool) – When the module that implements this function is uninstalled, this decorated method will be called. It should nearly always be False to prevent those errors from occurring upon module uninstalling.

    at_uninstall (bool) – 当卸载实现此功能的模块时,将调用此装饰方法。它几乎总是为False,以防止在卸载模块时发生这些错误。

    @api.returns(model, downgrade=None, upgrade=None)

    For methods that return model instances return a decorator.

    对于返回模型实例的方法,返回一个装饰器。

    Parameters

    参数

    · model – For the current model, a model name or'self'

    · model – 对于当前模型,模型名称或“self”

    · downgrade – The fuction, downgrade(self, value, *args, **kwargs) that converts a record-style value to the traditional-style output.

    · downgrade – 函数降级(self、value、*args、**kwargs)将记录样式值转换为传统样式输出。

    · upgrade – A function upgrade(self, value, *args, **kwargs) is used to convert a traditional-style value to a record-style output.

    · upgrade – 函数升级(self、value、*args、**kwargs)用于将传统样式值转换为记录样式输出。

     

    The parameters self, *args, and **kwargs are passed to the method in the record style.

    参数self、*args和**kwargs以记录样式传递给方法。

    The decorator modifies the method's output to be in the api style: id, ids, or False for the traditional form style and the recordset for the record style.

    装饰器将方法的输出修改为api样式:对于传统表单样式为id、ids或False,对于记录样式为记录集。

    @model

    @returns('res.partner')

    def find_partner(self, arg):

        # return some record

    # output depends on call style: traditional vs record style

    partner_id = model.find_partner(cr, uid, arg, context=context)

    # recs = model.browse(cr, uid, ids, context)

    partner_record = recs.find_partner(arg)

    It should be noted that the decorated method must satisfy to that convention.

    应该指出的是,装饰方法必须满足该惯例。

    Those decorators are automatically inherited: A method that overrides an existing decorated method will be decorated in the same way.@returns(model).

    这些装饰器是自动继承的:覆盖现有装饰方法的方法将以相同的方式进行装饰。@returns(model)

    本文章从网上收集,如有侵权请联系tderp@tderp.com删除
  • 微信扫一扫,一分也是爱:
  • 微信

服务原则及地区范围

宜兴通达网络科技有限公司,地处中国宜兴环科园内,是一家高新技术企业。公司在企业网络维护和企业信息化建设与咨询方面,有10多年经验。

我公司愿与客户一道,力求彻底解决客户问题!
我们不是在给企业提供“头痛医头、脚痛医脚”的暂时解决方案,而是在部署根本性安全与稳定服务!!
我们愿携手客户,建立企业IT规划;杜绝随意安装系统、软件等操作;力求共同维护有序、安全、稳定的网络办公环境!!!
IT服务,服务是根本,客户是上帝;我们提供快速响应、快速上门、快速排查,提供优质高效的服务!!!!

通达科技提供全国范围内的服务,服务形式包括远程协助、电话咨询、电子邮件咨询、传真咨询、问答平台的问题解决等。

宜兴地区提供上门服务:

  • 市区服务:宜城街道、城北街道(屺亭街道)、新街街道、新庄街道、环科园、渚桥开发区
  • 市郊服务:张渚镇、西渚镇、太华镇、徐舍镇、官林镇、杨巷镇、新建镇、和桥镇、高塍镇、万石镇、周铁镇、芳桥镇、丁蜀镇、湖父镇。
  • 联系电话:189-21-343434
  • 在线沟通: