在ERP開發過程中經常會使用到某字段的值是由其他字段計算得來,並且有些還需要將計算的結果存入資料庫。 以上功能上OpenERP中是用field.function實現的 其中有種模式 a). 只計算,不存儲 這種方式比較簡單,只需要設定用來計算值的函數即可,函數分類method和function,method是指當前對象的方法,function是指一般的python函數,有特定簽名的函數 [python] view plaincopy ‘amount‘: fields.function(_amt,string=‘caption‘,method=True,type=‘float‘) If method is true, the signature of the method must be: def fnct(self, cr, uid, ids, field_name, field_value, arg, context): otherwise (if it is a global function), it should be: def fnct(cr, table, ids, field_name, field_value, arg, context): b).計算,並且要將計算的結果存儲到資料庫,然後在相關的字段發生變更時進行重算 此模式需要指定store參數 store Parameter It will calculate the field and store the result in the table. The field will be recalculated when certain fields are changed on other objects. It uses the following syntax: store = { ‘object_name‘: ( function_name, [‘field_name1‘, ‘field_name2‘], priority) } It will call function function_name when any changes are written to fields in the list [‘field1‘,‘field2‘] on object ‘object_name‘. The function should have the following signature: def function_name(self, cr, uid, ids, context=None): Where ids will be the ids of records in the other object‘s table that have changed values in the watched fields. The function should return a list of ids of records in its own table that should have the field recalculated. That list will be sent as a parameter for the main function of the field. 请注意,function_name必须要能返回主函数所需要的ids的列表,即主函数的对象ID列表,而不是object_name所指的对象id. [‘field_name1‘, ‘field_name2‘], 执行时,当发生属性变更事件,会进行比对object_name以及[‘field_name1‘, ‘field_name2‘],是否match,当成功match,将执行function_name,并以当前发生变更的对象id为参数 Here‘s an example from the membership module: ‘membership_state‘: fields.function( _membership_state, method=True, string=‘Current membership state‘, type=‘selection‘, selection=STATE, store={ ‘account.invoice‘: (_get_invoice_partner, [‘state‘], 10), ‘membership.membership_line‘: (_get_partner_id,[‘state‘], 10), ‘res.partner‘: ( lambda self, cr, uid, ids, c={}: ids, [‘free_member‘], 10) }), c).函數一次為多個計算字段提供值,設定multi=‘groupname‘ multi is a group name. All fields with the same multi parameter will be calculated in a single function call. 函數的返回值格式需要調整為 [python] view plaincopy {id:{‘field1‘:value1},{‘field2‘:value2}, id2:{‘field1‘:value1},{‘field2‘:value2} } 這種模式比較不用擔心,如何去計算,何時去計算的問題,不過,如果計算值依賴於其他計算值時,就特別需要留意store裏面的priority參數 [python] view plaincopy store = { ‘object_name‘: ( function_name, [‘field_name1‘, ‘field_name2‘], priority) } 为提高执行效率,减少代码执行次数,这是有效的办法
OpenERP函數字段的應用
时间: 2024-11-06 03:28:44