odoo - 按categ_id 过滤行并计算数量
问题描述
我的目标是遍历所有具有相同categ_id 的行并计算它们的总数量和if qty_categ_total < categ_id.qty_for_discount
(我将此字段添加到'product.category'而不是我需要在文本字段中发布消息。我的代码无法正常工作的问题我想。
例子。
如果我有 2 行与categ_id
qty 2 和 5 相同,而我categ_id.qty_for_discount
是 10。消息应该说我需要添加 3 个相同的产品categ_id
才能获得折扣
更新
如果有不同类别的产品,我应该收到每个类别的消息
class PurchaseOrder(models.Model):
_inherit = 'purchase.order'
discount_warning_message = fields.Text(string='Discount Warning', compute='discount_warning')
@api.depends('order_line.product_id', 'order_line.product_qty')
def discount_warning(self):
qty_categ_total = 0.0
for line in self.order_line:
qty_categ_total += line.product_qty
if qty_categ_total < line.product_id.categ_id.qty_for_discount:
message = (_("You can get discount if you add %s more %s\n")) % (qty_categ_total, line.product_id.categ_id.name)
self.discount_warning_message = message
解决方案
你的代码似乎是正确的,但我会改变一些东西。首先要么使用@api.one
让 odoo 自动循环遍历所有订单,要么为每个循环添加一个,然后@api.multi
. 其次,不止一个类别呢?
@api.multi
@api.depends('order_line.product_id', 'order_line.product_qty')
def discount_warning(self):
msg = _("You can get discount if you add %s more %s\n")
for order in self:
categ_qtys = {}
for line in order.order_line:
if line.product_id.categ_id not in categ_qtys:
categ_qtys[line.product_id.categ_id] = 0.0
categ_qtys[line.product_id.categ_id] += line.product_qty
msgs = []
for categ, qty in categ_qtys.iteritems():
if qty < categ.qty_for_discount:
msgs.append(msg % (qty, categ.name))
if msgs:
order.discount_warning_message = "".join(msgs)
一般建议:始终尝试调试您的方法。他们甚至被称为?如果没有,方法不是问题。