我对函数字段值返回什么?

Wil*_*ino 5 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 = {}
        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 {}
Run Code Online (Sandbox Code Playgroud)

字段定义:

'expenses'      : fields.function(
                _property_expense_preset_expenses,
                type='one2many',
                obj="property.expense",
                method=True,
                string='Expenses'
            ),
Run Code Online (Sandbox Code Playgroud)

上面的代码不起作用,它引发了一个错误: KeyError: 788

Adr*_*all 6

与所有函数字段一样,它必须返回一个字典,其中包含您在id中传递的每个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
Run Code Online (Sandbox Code Playgroud)

假设id包含1,2,3,你将获得{1:[...],2:[...],3:[]}的结果

每个列表包含费用的整数ID,如果没有,则列出空列表.

作为一般性评论,我注意到你的代码没有将context参数默认为None,或者将上下文作为命名参数传递给browse方法 - 两者都很重要.