Xodoo第三节

 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

  • 28
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DTCloud4

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值