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

Odoo修改stock.quant现有数量失败,是否受内置机制限制?

问题解答

代码中的潜在问题

你提供的代码存在逻辑匹配错误:搜索stock.quant时用的是('location_id', '=', record.x_studio_tools.id),但后续又判断quant.location_id == location(location是record.x_studio_stock_location),明显是把产品字段和库存地点字段搞混了。正确的搜索条件应该同时匹配目标产品+对应库存地点,示例如下:

quant = env['stock.quant'].search([
    ('product_id', '=', record.x_studio_tools.id),
    ('location_id', '=', location.id)
], limit=1)

这个错误会导致找不到正确的库存记录,直接导致后续修改操作无法执行。

Odoo是否有预编码阻止直接修改quant?

是的,Odoo库存模块有多重机制限制直接修改stock.quant的quantity字段:

  • 数据库约束:stock.quant内置_check_quantity约束,默认禁止库存数量变为负数(除非系统开启了允许负库存的设置)。
  • 业务逻辑拦截:直接修改quant会绕过库存系统的核心流程,比如库存移动轨迹记录、成本估值计算、上下游模块(MRP、销售等)的联动触发。部分版本中stock.quant的write方法被重写,强制要求通过标准库存操作修改数量。
  • 权限与规则校验:即便使用sudo()提升权限,不符合库存业务规则的操作仍会被底层逻辑拦截。

是否必须通过库存调整流程修改库存?

不是必须,但强烈推荐使用标准流程——直接修改quant会破坏库存数据的一致性,导致系统内库存轨迹、成本统计等信息失真。

合法修改库存的标准方式有两种:

  1. 库存调整(Inventory Adjustment):创建stock.inventory记录,指定产品、库存地点和调整后数量,系统会自动生成库存移动并更新quant,同时留存调整日志。
  2. 创建库存移出动作:手动创建stock.move记录,设置产品、数量、来源地点(待减库存的地点)、目标地点(如报废/中转地点),确认移动后系统自动更新库存并维护完整变动轨迹。

如果要在服务器动作中实现库存减少,建议调用标准API而非直接修改quant,示例代码如下:

for record in records:
    product = record.x_studio_tools
    location = record.x_studio_stock_location
    quant = env['stock.quant'].search([
        ('product_id', '=', product.id),
        ('location_id', '=', location.id)
    ], limit=1)
    if quant and quant.quantity > 0:
        # 创建库存调整单
        inventory = env['stock.inventory'].create({
            'name': f'调整{product.name}库存',
            'product_id': product.id,
            'location_id': location.id,
            'state': 'draft'
        })
        inventory.action_start()
        # 设置调整后数量
        inventory.line_ids.write({'product_qty': quant.quantity - 1})
        inventory.action_validate()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 03:22:48