宜兴通达竭诚为您服务。

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

Constraints
  • 上传者: Administrator
  • 上传时间:2023年11月14日 01时16分10秒
摘要:
* Constraints ** *** * 约束条件 ** *** Any real-world business scenario has a chance that users provide inaccurate data. Constraints allow us to stop u ......
正文 相关文章 请喝咖啡

    Constraints

    约束条件

    Any real-world business scenario has a chance that users provide inaccurate data. Constraints allow us to stop users from submitting inaccurate data. In order to prevent inaccurate data from being recorded before the record is saved, constraints are limits set on the record.

    任何现实世界的业务场景都有可能用户提供不准确的数据。约束允许我们阻止用户提交不准确的数据。为了防止在保存记录之前记录不准确的数据,对记录设置了限制。

    Two approaches

    两种途径

    The two tools given by Odoo for automatically validating invariants are Python Constraints and SQL Constraints.

    Odoo提供的用于自动验证不变量的两个工具是Python约束和SQL约束。

    SQL Constraints:

    SQL约束:

    SQL Constraints are defined on the model using the class attribute _sql_constaints. This belongs to the part of PostgreSQL.

    SQL约束是使用类属性_SQL_constants在模型上定义的。这属于PostgreSQL的一部分。

    Syntax for writing SQL Constraints:

    编写SQL约束的语法:

    _sql_constraints = [(name, sql_def, message)]

    name: SQL Constraints name.

    name: SQL约束名称。

    sql_def: PostgreSQL syntax of the constraint.

    sql_def: PostgreSQL语法约束。

    message: error message.

    message:错误消息。

    For example,

    例如

    sql_constraints = [('date_order_conditional_required', "CHECK( (state IN ('sale', 'done') AND date_order IS NOT NULL) OR state NOT IN ('sale', 'done') )", "A confirmed sales order requires a confirmation date."),]

    This is the sql_constraints taken from the sale order. It aims to verify the confirmed sale order has a confirmation date. If the sql_constraints fails, then it will show an error message. The SQL constraint will always be specified in the field declaration section of the Python code; it is defined before entering the coding section.

    这是从销售订单中提取的sql_conconstraints。其目的是验证确认的销售订单是否有确认日期。如果sql_conconstraints失败,则会显示错误消息。SQL约束将始终在Python代码的字段声明部分指定;它在进入编码部分之前被定义。

    Python Constraints:

    Python约束:

    Data consistency can be efficiently ensured using SQL constraints. To ensure data consistency in other situations, we might need to utilize more complicated tests. In such situations, we can use python constraints.

    使用SQL约束可以有效地确保数据一致性。为了确保其他情况下的数据一致性,我们可能需要使用更复杂的测试。在这种情况下,我们可以使用python约束。

    The Python constraint is a method decorated with constraints(). It is included on a record of the set. Decorators are used to specifying which fields are involved in the constraints. When a field is changed, these constraints are automatically considered.

    Python约束是一个用constraints()修饰的方法。它被收录在该集的记录中。装饰符用于指定约束中涉及哪些字段。更改字段时,会自动考虑这些约束。

    For example,

    例如,

    @api.constrains('product_id')

    def check_product_is_not_kit(self):

       if self.env['mrp.bom'].search(['|', ('product_id', 'in', self.product_id.ids), '&', ('product_id', '=', False), ('product_tmpl_id', 'in', self.product_id.product_tmpl_id.ids),('type', '=', 'phantom')], count=True):

           raise ValidationError(_("A product with a kit-type bill of materials can not have a reordering rule."))

    It is the sql_constraints that were taken from the warehouse, and it checks to make sure that any reordering rules cannot apply to a product with a kit-type bill of materials. If it doesn't work, an error message appears.

    这是从仓库中提取的sql_constrains,它会进行检查以确保任何重新订购规则都不能适用于具有套件类型物料清单的产品。如果不起作用,将显示错误消息。

    Computed Fields

    计算字段

    In any real-world business scenario, there are some fields with values derived from other fields. The calculated values are either from the same records or from records that are connected to them. We can take advantage of computed fields in this situation. We can use an Odoo function to calculate the values for the fields.

    在任何现实世界的业务场景中,都有一些字段的值来自其他字段。计算值要么来自相同的记录,要么来自与其连接的记录。在这种情况下,我们可以利用计算字段。我们可以使用Odoo函数来计算字段的值。

    Computed fields in Odoo have the same definition as other ordinary fields in Odoo. The attribute calculate, which is used to give the name of the function used for its computation, is the only exception. At runtime, computed fields are dynamically calculated. Unless you add such support directly by yourself, they are not searchable or writable.

    Odoo中的计算字段与Odoo中的其他普通字段具有相同的定义。属性calculate是唯一的例外,它用于给出用于其计算的函数的名称。在运行时,计算字段是动态计算的。除非您自己直接添加此类支持,否则它们无法搜索或写入。

    A computed field has the same attribute ‘compute’ as other normal fields when it is declared. The name of the function as a string or as a function is the value for the compute attribute.

    当声明计算字段时,它与其他普通字段具有相同的属性“compute”。作为字符串或函数的函数名称是compute属性的值。

    Dependencies:

    依赖关系:

    Usually, the values of other fields affect the values of computed fields. Therefore, using the decorator depends(), we can define those requirements on the compute method. At runtime, the computation function performs dynamic calculations. We must avoid from recalculating the value inefficiently.

    通常,其他字段的值会影响计算字段的值。因此,使用装饰器depends(),我们可以在计算方法上定义这些要求。在运行时,计算函数执行动态计算。我们必须避免低效地重新计算这个值。

    Hence, it needs to be aware of the other fields that depend on it and must include those fields in the decorator depends ().

    因此,它需要知道依赖于它的其他字段,并且必须在装饰器depends()中包含这些字段。

    For example,

    例如,

    amount = fields.Float('Amount')

    total = fields.Float('Total', compute="_compute_total")

    @api.depends('amount')

    def _compute_total(self):

       for rec in self:

           rec.total = 2.0 * rec.amount

    Here, we can calculate the total by using the function _compute_total. By default, computed fields are not kept in the database. In order to store the record in the database, we can use the store property.

    在这里,我们可以使用函数_computer_total计算总和。默认情况下,计算字段不保存在数据库中。为了将记录存储在数据库中,我们可以使用store属性。

    We can use the store = True flag

    我们可以使用store=True标志

    For example,

    例如,

    total = fields.Float('Total', compute="_compute_total", store=True)

    So, rather than having to be recomputed at runtime, they may be obtained just like any other regular fields. The ORM will be able to determine when these stored values need to be updated and recalculated.

    因此,不必在运行时重新计算,它们可以像任何其他常规字段一样获得。ORM将能够确定何时需要更新和重新计算这些存储值。

    Inverse Function

    反函数

    We know that by default, the computed fields are read-only. Which means the user couldn’t set the value for the computed fields. In some cases, it might be useful to still be able to set a value directly. For that, Odoo provides the ability to use an inverse function:

    我们知道,默认情况下,计算字段是只读的。这意味着用户无法为计算字段设置值。在某些情况下,仍然能够直接设置值可能是有用的。为此,Odoo提供了使用函数的能力:

    total = fields.Float(compute="_compute_total",    inverse="_inverse_total")

    amount = fields.Float()

    @api.depends("amount")

        def _compute_total(self):

            for record in self:

                record.total = 2.0 * record.amount

        def _inverse_total(self):

            for record in self:

                record.amount = record.total / 2.0

    The field is set by a compute method, and the field's dependencies are generated by an inverse method. When saving a record, the inverse method is called, and the compute method is activated whenever one of its dependencies changes.

    该字段由计算方法设置,字段的依赖关系由逆方法生成。保存记录时,会调用逆方法,每当其依赖关系之一发生变化时,计算方法就会被激活。

    Related Fields

    关系字段

    We need to demonstrate the benefit of a field from a relational model to the current model in any real-world business scenario where we have some fields. In such a situation, we can use related fields. To do that, we need to specify the attribute related.

    我们需要在任何有字段的现实业务场景中,展示从关系模型到当前模型的字段的好处。在这种情况下,我们可以使用相关字段。为此,我们需要指定相关的属性。

    For example, we have a Many2one field partner_id, and its comodel is res.partners, and a related field is partner_name:

    例如,我们有一个Many2one字段partner_id,它的comodel是res.partners,一个相关字段是partner_name:

    partner_id = fields.Many2one('res.partners')

    partner_name = fields.Char('Name', related="partner_id.name")

    Related fields are read-only and not copied by default, nor are they stored in the database. Using the store = True attributes, we can store the field record in the database.

    相关字段是只读的,默认情况下不会复制,也不会存储在数据库中。使用store=True属性,我们可以将字段记录存储在数据库中。

    partner_name = fields.Char('Name', related="partner_id.name", store=True)

    Reference Fields

    参考字段

    We have different types of relational models, many2one, one2many, and many2many. In relational models, we can create relationships between different models. A reference field helps us to create dynamic relationships between models. Relational models only permit the relationship between the two models by defining a related comodel in advance. However, if we utilize the reference field type, the user can select a related model from a list of options and a related record from that model.

    我们有不同类型的关系模型,many2one、one2many和many2many。在关系模型中,我们可以在不同模型之间创建关系。参考字段帮助我们在模型之间创建动态关系。关系模型只允许通过预先定义相关的共模型来建立两个模型之间的关系。但是,如果我们使用引用字段类型,用户可以从选项列表中选择相关模型,并从该模型中选择相关记录。

    We must first choose the target model before choosing the record in the reference field. For instance, let's say we need a field reference. We may sometimes need to choose a manufacturing order, sale order, or purchase order as a reference. We can use Reference fields in this situation.

    在选择参考字段中的记录之前,我们必须首先选择目标模型。例如,假设我们需要一个字段引用。我们有时可能需要选择生产订单、销售订单或采购订单作为参考。在这种情况下,我们可以使用引用字段。

    reference_field = field.Reference(selection='', string='field name')

    为此,我们使用选择参数。我们必须将模型及其名称分配给此参数。

    例如,

    reference = fields.Reference(selection="[('sale.order', 'Sale Order'), ('purchase.order', ' Purchase Order')]", string="Reference")

    Here, we can choose a Sale Order or Purchase Order, from the same field. Also possible to selection from a function.

    reference = field.Reference(selection="get_model")

    @api.model

    def get_model(self):

       models = self.env['ir.model'].search([])

       return [(model.model, model.name), for model in models]

    Returned values must be a list

    返回的值必须是列表

    Abstract Model

    抽象模型

    Main super-class for regular database-persisted Odoo models.

    常规数据库的主超类持久化Odoo模型。

    All Odoo models are created by inheriting from this class:

    所有Odoo模型都是通过继承这个类创建的:

    from . import models, fields

    class AbstractModel(models.AbstractModel):

       _name = "model name"

       Field = fields.Char(string="field label")

    Transient model

    态模型

    Model super-class for transient records, intended to be only temporarily persistent, that are regularly vacuum-cleaned.

    用于瞬态记录的模型超级类,旨在仅暂时持久,并定期进行真空清洗。

    A temporary paradigm has made it easier to manage access rights. New records can be made by any user at any time. They can only access the records they have created, though. The superuser has unrestricted access to all Transient Model records

    临时范式使管理访问权限变得更加容易。任何用户都可以随时创建新记录。不过,他们只能访问自己创建的记录。超级用户可以不受限制地访问所有瞬态模型记录

    from . import models, fields

    class TransientModel(models.Transientmodel):

    _name = "model name"

    Field = fields.Char(string="field label")

     


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

服务原则及地区范围

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

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

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

宜兴地区提供上门服务:

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