You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Odoo库存更新向导中按产品和库存位置过滤lot批次可选值

Odoo 库存向导批次字段过滤实现方案

核心逻辑

stock.production.lot(批次模型)本身没有直接关联stock.location(库存位置模型),二者的对应关系存储在stock.quant(库存明细模型)中,因此需要通过stock.quant作为中间表过滤符合条件的批次。

实现方法一:onchange 动态设置domain(全版本兼容,性能最优)

步骤1:定义向导模型字段

from odoo import models, fields, api

class StockUpdateWizard(models.TransientModel):
    _name = 'stock.update.wizard'
    _description = '库存更新向导'

    product_id = fields.Many2one('product.product', string='产品', required=True)
    location_id = fields.Many2one('stock.location', string='库存位置', required=True)
    lot_id = fields.Many2one('stock.production.lot', string='批次')

步骤2:新增onchange监听方法

监听产品和库存位置字段的变更,动态查询符合条件的批次并设置domain:

@api.onchange('product_id', 'location_id')
def _onchange_filter_lot(self):
    # 默认按选中产品过滤批次
    lot_domain = [('product_id', '=', self.product_id.id)]
    if self.location_id and self.product_id:
        # 查询当前产品、当前位置下的所有关联批次
        quant_lots = self.env['stock.quant'].search([
            ('location_id', '=', self.location_id.id),
            ('product_id', '=', self.product_id.id),
            # 若需要过滤掉库存为0的批次,保留下面这行条件,不需要则删除
            ('quantity', '>', 0),
        ]).lot_id
        lot_domain.append(('id', 'in', quant_lots.ids))
    # 给lot_id返回过滤后的domain
    return {'domain': {'lot_id': lot_domain}}

实现方法二:视图直接写domain(无需Python代码,适配Odoo12+)

如果不想修改Python代码,可以直接在向导的XML视图中给lot_id字段配置domain:

<field name="lot_id" domain="[
    ('product_id', '=', product_id),
    ('id', 'in', [quant.lot_id.id for quant in env['stock.quant'].search([
        ('location_id', '=', location_id),
        ('product_id', '=', product_id),
        ('quantity', '>', 0) # 不需要过滤零库存批次可删除此行
    ])])
]" />

注意:该方式每次字段变更都会实时触发查询,数据量较大时性能低于第一种方法,仅适合小批量数据场景。


可选调整规则

  • 若需要包含所选库存位置的所有子位置下的批次,将stock.quant查询条件中的('location_id', '=', xxx)改为('location_id', 'child_of', xxx)
  • 若允许负库存的批次可选,删除('quantity', '>', 0)过滤条件即可

内容的提问来源于stack exchange,提问作者shahinshah ummer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 08:06:00