python - Odoo:one2many 字段仍然添加记录,即使我在零库存时引发错误
问题描述
所以这个想法是当我改变产品时,它会检查当前分支上可用的库存,如果没有,它会引发没有库存的错误
预期行为:当所选产品没有可用库存时引发错误,如果没有可用库存,则不会将记录添加到树视图
当前行为:当所选产品上没有可用库存但记录仍被添加到 one2many 树视图时引发错误
下面的代码
# -*- coding: utf-8 -*-
from docutils.nodes import line
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError
class CustomTransRequest(models.Model):
_name = 'custom.trans.request'
_description = 'Transfer Request'
user_id = fields.Many2one('res.users', string='Salesperson', default=lambda self: self.env.user)
branch_from_id = fields.Many2one('custom.branch', string="From", required=True)
branch_to_id = fields.Many2one('custom.branch', string="To", required=True)
product_ids = fields.One2many(comodel_name="custom.trans.line", inverse_name="request_id", string="Products",
required=False, )
class CustomTransLine(models.Model):
_name = 'custom.trans.line'
_description = 'Transfer Request Line'
branch_from_id = fields.Many2one(comodel_name="custom.branch", string="Branch", )
request_id = fields.Many2one("custom.trans.request", string="Request ID", )
product_id = fields.Many2one("custom.product", string="Product", required=True, )
qty = fields.Integer(string="Qty")
@api.onchange('product_id')
def onchange_product(self):
if self.product_id:
for rec in self:
selected_lines = rec.env['custom.branch.line'].search(
['&', ('product_id', '=', rec.product_id.id), ('branch_id', '=', rec.branch_from_id.id)]).mapped(
'qty')
if not selected_lines:
raise ValidationError(
_('Current branch has ZERO stock on this product, Please select an available Product'))
解决方案
如果您不想记录到 one2many 字段中,请设置product_id=False
. 并返回验证字典。
尝试使用以下代码。
@api.onchange('product_id')
def onchange_product(self):
if self.product_id:
res = {}
selected_lines = rec.env['custom.branch.line'].search(
['&',
('product_id', '=', self.product_id.id),
('branch_id', '=', self.branch_from_id.id)]).mapped('qty')
if not selected_lines:
self.product_id = False
res['warning'] = {'title': _('ValidationError'),
'message': _(
'Current branch has ZERO stock on this product, '
'Please select an available Product')}
return res
推荐阅读
- excel - While 函数 - 根据变量迭代地添加天/月,占每个月的最大天数
- html - 为什么我的引导网格有太多边距?
- javascript - 如何在百里香中解析正则表达式?
- c# - 提交代码后从另一个页面关闭 iframe
- javascript - 我正在创建一个密码生成器并且在 javascript 上遇到了一些问题
- c# - 如何让卡片淡入淡出 C# / WPF / MaterialDesign
- python - 令人尴尬的并行和 Tensorflow 2.0
- node.js - 将现有标签/段添加到联系人
- spring-boot - 带弹簧靴的 Tibco jms
- pandas - 如何从我的数据框输出中删除 \n?