Skip to content

Odoo上下文经典用途

概述

Odoo中的上下文有很多用处,这个小作文介绍其中的一个应用场景,也许你看完之后也会感觉挺有意思的,以后做开发方案的时候能想到使用上下文。

产品的各种数量

你知道Odoo的产品有几个数量类的字段?我想排在第一位的肯定是”在手数量“,其次是”预测数量“,还有什么?

  • 免费使用数量(哈哈,由于中文用户数量少得不到重视,加上该字段常用于逻辑中,界面上不常用,所以翻译成这个鬼样子了,英文为Free To Use Quality)

  • 入库(机械的不能再机械了,官方写一个Incoming,你就翻译成入库?帮助信息的第一句就是:Quantity of planned incoming products. 意思是待入库产品数量。)

  • 出库(这个就不再说了,跟入库相反)

这四个数量是通过一个计算方法得到的,其中用到了上下文(context)。

python
products = self.filtered(lambda p: p.type != 'service')
res = products._compute_quantities_dict(self._context.get('lot_id'), self._context.get('owner_id'), self._context.get('package_id'), self._context.get('from_date'), self._context.get('to_date'))
for product in products:
    product.update(res[product.id])

代码不解析了,上下文这个事情属于没啥难度,但是你得知道且有意识的取用!

python
def _compute_quantities_dict(self, lot_id, owner_id, package_id, from_date=False, to_date=False):
    domain_quant_loc, domain_move_in_loc, domain_move_out_loc = self._get_domain_locations()
    ...

库位的过滤由于涉及到父子关系,所有有单独的方法来处理。

python
location = self.env.context.get('location')
if location and not isinstance(location, list):
    location = [location]
warehouse = self.env.context.get('warehouse')
if warehouse and not isinstance(warehouse, list):
    warehouse = [warehouse]

这样你就知道报告-库存这个界面,点击左侧的仓库为啥会影响在手数量的值了。