Openerp 我应该为函数字段值返回什么?
我有一个函数字段,但我不知道该函数返回什么 这是我的密码: 职能:Openerp 我应该为函数字段值返回什么?,openerp,openerp-7,Openerp,Openerp 7,我有一个函数字段,但我不知道该函数返回什么 这是我的密码: 职能: def _property_expense_preset_expenses(self, cr, uid, ids, expenses, arg, context): spus = self.browse(cr, uid, ids) _spu = False for spu in spus: _spu = spu if(_spu): expenses_acc = {}
def _property_expense_preset_expenses(self, cr, uid, ids, expenses, arg, context):
spus = self.browse(cr, uid, ids)
_spu = False
for spu in spus:
_spu = spu
if(_spu):
expenses_acc = {}
property_expense_presets = _spu.property_expense_presets
for property_expense_preset in property_expense_presets:
expenses = property_expense_preset.expense_preset.expenses
for expense in expenses:
expenses_acc[expense.id] = expense
return expenses_acc
else:
return {}
字段定义:
'expenses' : fields.function(
_property_expense_preset_expenses,
type='one2many',
obj="property.expense",
method=True,
string='Expenses'
),
上面的代码不起作用,它引发了一个错误:KeyError:788
什么是函数字段?返回这个函数字段的函数是什么?
在OpenERP中,功能字段是一个字段,它返回存储在表中的计算值/逻辑值。您无法直接获取该值这就是为什么我们希望使用函数字段并返回一些值
将数据插入对象模型功能字段时,每次调用定义的函数和该函数逻辑代码,然后返回该功能字段值
例子
上述示例代码分支名称(如saas/demo/rarone)
已存在于另一个表中
但是我想在字符串
(rarone)
之后只获取分支名称最后一个斜杠(/)
,并只将其存储到这个表中。
与所有函数字段一样,它必须返回一个字典,其中包含在ids中传递的每个ID的条目和值,尽管您的值可以为False、None、[]
在您的情况下,函数字段被声明为one2many类型,这意味着您的函数字段必须返回一个字典,其中包含每个id的条目和值,以及一个表示相关表id的整数列表,在您的情况下为property.expense
一个非常常见的模式是:
def _property_expense_preset_expenses(self, cr, uid, ids, field, arg, context = None):
res = {}
for spu in self.browse(cr, uid, ids, context = context):
res[spu.id] = []
for preset in spu.property_expense_presets:
res[spu.id].extend([x.id for x in preset.expense_preset.expenses])
return res
假设ids包含1,2,3,您将得到
{1:[…],2:[…],3:[…]
其中,每个列表包含费用的整数ID,如果没有,则为空列表
作为一般性评论,我注意到您的代码没有将上下文参数默认为None,也没有将上下文作为命名参数传递给browse方法-两者都要做很重要。您能给我举一个one2many类型的示例吗?当我使用type='one2many'
时,我应该为r[branch.id]=
设置什么值。很抱歉,您描述的第一句话没有意义。对于您的要求,我想做一个演示示例。这现在不可能,对不起。即使我做了,我还是把它放在这里。你能告诉我如何处理费用对象吗?该对象已经可用,并且已经设置为费用\u acc[expense.id]
?我的代码已经和你的相似了。它只需要对费用对象进行一点调整,因为idk知道如何处理它。@William我对此很了解,但我主要在controller或web上工作,所以我建议你现在就提问,这才是真正的答案!谢谢你,伙计。但是你错过了
的
之前的
res={}
。哈,很好,先生!这将教会我在火车上匆忙回答。
def _property_expense_preset_expenses(self, cr, uid, ids, field, arg, context = None):
res = {}
for spu in self.browse(cr, uid, ids, context = context):
res[spu.id] = []
for preset in spu.property_expense_presets:
res[spu.id].extend([x.id for x in preset.expense_preset.expenses])
return res