当前位置: 首页 > 知识教程 > 在OpenERP报表中使用selection 类型字段
在OpenERP报表中使用selection 类型字段
Odoo,OpenERP中文网 / 2013-11-22

 OpenERP 在报表的创作中始终有一个麻烦,那就是在报表中通过对象导航的方式获取的 selection 字段只能获取到该字段的 key 而不能获取对应的用户友好的描述文本。

举个具体的例子:销售单的 state 字段,在报表中使用 [[ object.state ]] 引用时,系统返回的将是 'draft', 'manual', 'confirmed' 等内部使用的 key,而不是对应的“草稿”、“手工”和“已确认”。由于报表是供业务人员打印及浏览,所以出现系统内部代码是完全不可接受的。

此问题 OpenERP SA 公司官方并没有提供理想的解决方案,许多系统内置的报表就直接显示了 selection 字段内部的 key。但是多亏了伟大的社区,aeroo_report 模块提供了一段非常好用的代码:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def _get_selection_items(self, kind='items'):
    def get_selection_item(obj, field, value=None):
        try:
            if isinstance(obj, report_sxw.browse_record_list):
                obj = obj[0]
            if isinstance(obj, (str,unicode)):
                model = obj
                field_val = value
            else:
                model = obj._table_name
                field_val = getattr(obj, field)
            if kind=='item':
                if field_val:
                    return dict(self.pool.get(model) \
                    .fields_get(self.cr, self.uid, allfields=[field], context=self.context)\
                    [field]['selection'])[field_val]
            elif kind=='items':
                return self.pool.get(model) \
                .fields_get(self.cr, self.uid, allfields=[field], context=self.context)\
                [field]['selection']
            return ''
        except Exception:
            return ''
    return get_selection_item

只要把以上代码加入你的报表 parser,并在构造函数 __init__() 中将其以如下格式注册到 localcontext 中:

 
1
2
'get_selection_item':self._get_selection_items('item'),
'get_selection_items': self._get_selection_items(),

以后在报表中调用 get_selection_item 函数即可获得 selection 字段值所对应的描述字符串:

 
1
[[ get_selection_item(object, 'state') ]]

为方便大家的使用,我们公司正在开发一个通用的模块,以后只需直接安装此模块即可提供 get_selection_item 函数的支持。当然了,更好的办法是抛弃系统内置的报表引擎,像我们的OpenERP一样改为使用效率更高、对本地化支持更好的 OpenOffice/LibreOffice 格式报表引擎 aeroo_report。