Monetary
Odoo中有一类字段Monetary用于计算跟货币相关的运算,定义为Monetary的字段需要与货币(Currency_id)关联计算,
Monetary的字段是带有一个参数 currency_field的,该参数的作用是用来指明 Monetary字段运算时的精度和货币单位需要参考的字段,默认为 'currency_id'.
如果定义了Monetary的字段就需要定义一个cunrrency_id(也可以为其他名称,但就需要在定义的时候带currency_field参数了)
即便是你同时定义了currency_id,也还需要你在XML中引用该字段才能是Monetary的精度和货币单位生效。
currency_id = fields.Many2one('res.currency', string='Currency')
rent_amount = fields.Monetary('Rent Amount', help="Enter rent amount per month")
#optional attribute: currency_field='currency_id'
属性 | 说明 |
---|---|
name | (通常为 Char)默认作为记录的显示名称。通过是一个 Char,但也可以是 Text 或Many2one字段类型。用作显示名的字段可修改为_rec_name模型属性。 |
active | (Boolean型)允许我们关闭记录。带有active=False的记录会自动从查询中排除掉。可在当前上下文中添加{‘active_test’: False} 来关闭这一自动过滤。可用作记录存档或假删除(soft delete)。 |
state | (Selection类型) 表示记录生命周期的基本状态。它允许使用states字段属性来根据记录状态以具备不同的 UI 行为。动态修改视图:字段可在特定记录状态下变为readonly, required或invisible。 |
active = fields.Boolean("Active")
嵌套集模型
首先要在模型的类属性中指定_parent_name字段,并且将_parent_store设置为True,以标识将该字段存储到数据库中以提高筛选效率
class HostelCategory(models.Model):
_name = "hostel.category"
_description = "Hostel Categories"
_parent_store = True
_parent_name = "parent_id"
......
然后定义三个字段,parent_id、parent_path和child_id(child_ids),parent_id的字段名称可以自己定义,但是要在_parent_name中标明,parent_path和child_id(child_ids)不可以变更。
parent_id = fields.Many2one(
'hostel.category',
string='Parent Category',
ondelete='restrict',
index=True)
parent_path = fields.Char(index=True, unaccent=False)
child_ids = fields.One2many( # 自关联
'hostel.category', 'parent_id',
string='Child Categories')
parent_path字段最好添加索引以加快查询速度
ondelete默认为set null
parent_id = fields.Many2one('hostel.category',string='Parent Category',ondelete='restrict',)
模型hostel.category进行delete操作时,会引发如下操作
set null: 当hostel.category中删除记录时,只删除自己,其他的不删除
cascade: 当hostel.category中删除记录时,模型相关记录也全部删除
restrict: 当hostel.category中删除记录时,如果modelA中存在对应记录,则无法删除
安装模块后可以在数据库中查看到这些字段的作用
装饰器约束constraints
装饰器参数指定了约束的字段,当涉及的字段中任一发生改变时触发方法执行。如果不满足约束条件,该方法将引发异常。
@api.constrains('parent_id')
def _check_hierarchy(self):
if not self._check_recursion():
raise models.ValidationError('错误!不能创建递归类别。')
每次记录修改的时候,如果包含了装饰器定义的字段就会触发下面的方法。使用constraints的时候就算是系统内已经有违反约束的记录也可以对新记录生效。
防止递归调用函数:_check_recursion